Home > Java > How is this possible in Java generics?

How is this possible in Java generics?

王林
Release: 2024-02-08 23:20:09
forward
1010 people have browsed it

php editor Apple will answer for you: In Java generics, the question "How is this possible in Java generics?" is actually possible. Because Java generics allow the use of wildcards to represent undefined types, such as using "?" to represent any type. When we define a generic method or generic class, we can use wildcards to limit parameter types or return value types to achieve some specific functions. Although in some cases, there may be some limitations due to type erasure, with reasonable design and use, we can achieve many seemingly impossible operations in Java generics.

Question content

I just noticed something that is very counterintuitive to me when it comes to Java generics. Let’s take a look at this method:

public static <T> void inspect(T a, T b) { // ... }
Copy after login

The following calls can be made:

inspect(new Integer(3), new String("What? How?"))
Copy after login

I think once the type T is derived, it must be consistent, just like two strings or two integers. This doesn't make much sense, because if I have the following line in my method:

T tmp
Copy after login

What is T?

Can anyone explain?

Solution

The main result is that both Integer and String are implemented from Serialized.

So your code equals:

public static <T extends Serializable> void inspect(T a, T b) {
    System.out.println(a + "_" + b);
}
Copy after login

If changed to blow code, only valid in Integer or Number subclasses.

public static <T extends Number> void inspect(T a, T b) {
    System.out.println(a + "_" + b);
}
Copy after login

Here's a better example:

public class MyTest {

    @Test
    public void demo() {
        inspect(new FirstSon("a"), new SecondSon("b"));
    }

    public <T> void inspect(T a, T b) {
        System.out.println(a + "_" + b);
    }


    interface Parent {
    }

    static class FirstSon implements Parent {
        private String name;

        public FirstSon(String name) {
            this.name = name;
        }
    }

    static class SecondSon implements Parent {
        private String name;

        public SecondSon(String name) {
            this.name = name;
        }
    }
}
Copy after login

The above is the detailed content of How is this possible in Java generics?. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template