private void readList(ArrayList list){
list.add("Hello");
list.add(2);
}
public void run(){
setFont("Courier-24");
ArrayList<Integer> list = new ArrayList<Integer>();
readList(list);
println("list = "+list);
println("Type of list[1] = "+list.get(1).getClass());
}
Result:
list = [Hello, 2]
Type of list[1]=class java.lang.Integer
public void run(){
setFont("Courier-24");
ArrayList<Integer> list = new ArrayList<Integer>();
readList(list);
println("list = "+list);
println("Type of list[0] = "+list.get(0).getClass());
}
Result:
list = [Hello, 2]
Exception in thread "Thread-2" java.lang.ClassCastException:
java.lang.String cannot be cast to java.lang.Integer
After reading something about type erasure
, I've got my guess:
When I call readList(list)
, it's actually adding things into list that is 'falsely' regarded as type ArrayList
so there is no error(this is my understanding of so-called type erasure
). But if I call println("Type of list = "+list.get(0).getClass());
in run()
there comes the error because list[0]
is of type String
(while println("Type of list = "+list.get(1).getClass());
doesn't because list[1] is of type Integer
).
Is it like some criminal escaped from crime scene at first (because he belongs to normal people and normal people has freedom), and later when police start to check everyone that was around then he got caught because he is a criminal in deep?