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

How is this possible in Java generics?

王林
王林forward
2024-02-08 23:20:09995browse

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) { // ... }

The following calls can be made:

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

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

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);
}

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);
}

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;
        }
    }
}

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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete