Wednesday, June 20, 2007

Strange Generic Problem

Today my colleague asked me a question about generic in Java.
Here's the code

package test;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class TestGeneric {
public static void main(String[] args)throws Exception{
List list = new ArrayList();
list.add("test");
List newList = list;
newList.add(4);
System.out.println(list.get(1));

List list2 = new ArrayList();
list2.add(new Date());
List newList2 = list2;
newList2.add("test");
System.out.println(list2.get(0));
}
}

And an exception was thrown when executing it.
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at test.TestGeneric.main(TestGeneric.java:13)


But if I commented out line 13,it works.The thing is quite weird as if the type casting rule is applied list,why doesn't it applied on list2?Obviously,we put an integer into a list which is expecting Date object,and when we print it,it wasn't cast to Data object.Then I decompiled the class file and this is what i get.

package test;

import java.io.PrintStream;
import java.util.*;

public class TestGeneric
{

public TestGeneric()
{
}

public static void main(String args[])
throws Exception
{
List list = new ArrayList();
list.add("test");
List newList = list;
newList.add(Integer.valueOf(4));
System.out.println((String)list.get(1));
List list2 = new ArrayList();
list2.add(new Date());
List newList2 = list2;
newList2.add("test");
System.out.println(list2.get(0));
}
}

We look at line "System.out.println((String)list.get(1));" ,value in list was typecast to String object,where as "System.out.println(list2.get(0));" the value in list2 wasn't typecast to Date object.

Any idea?

No comments: