Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yet another java generics confusion

Let us 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");
    }
}

In the output I get:

java.lang.String
java.lang.Integer

It's nonsense - we've just assigned Integer to String without getting ClassCastException! We can't write it like that:

String s = new Integer(3);

but this is what we have just done here.

Is it a bug or something?

like image 616
Denis Kniazhev Avatar asked Jun 14 '26 12:06

Denis Kniazhev


2 Answers

In your case as list is an ArrayList<Object>, T is considered as an Object so you can see things as :

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

So you assigned an Integer to an Object (which was a String before).

Object obj = new Integer(3);
obj = "Hello"; //No CCE here
like image 91
Colin Hebert Avatar answered Jun 16 '26 02:06

Colin Hebert


You have a list of Object. One of the objects in the list is a String, the other is an Integer. getClass returns the runtime type of the object, not the static type. There is no casting involved here.

like image 32
Mark Byers Avatar answered Jun 16 '26 03:06

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!