Another java generics confusion

We have the following code:

public class TestGenerics {
    static <T> void mix(ArrayList<T> list, T t) {
        System.out.println(t.getClass().getName());
        T item = list.get(0);
        t = item;
        System.out.println(t.getClass().getName());
    }
    public static void main(String[] args) {
        ArrayList<Object> list = new ArrayList<Object>();
        list.add(new Integer(3));

        mix(list, "hello world");
    }
}

At the output, I get:

java.lang.String
java.lang.Integer

This is nonsense - we just assigned Integerto Stringwithout receiving ClassCastException! We cannot write like this:

String s = new Integer(3);

but this is what we just did here.

Is this a mistake or something else?

+3
source share
3 answers

In your case, as listis ArrayList<Object>, it is Tconsidered as Object, so you can see things like:

 static void mix(ArrayList<Object> list, Object t)

So you assigned Integerto Object(it used to be String).

Object obj = new Integer(3);
obj = "Hello"; //No CCE here
+9
source

. - String, - Integer. getClass , . .

+2

It seems to me that it getClass()returns the dynamic (runtime) type of an object, while generics only has information about the static (compilation time).

What you type on the console are the actual dynamic types.

However, in your sample code it Twill be of type Object, therefore it t = itemis a perfectly valid destination.

+2
source

Source: https://habr.com/ru/post/1767644/


All Articles