I have the following piece of code
public static void main(String[] args) {
ArrayList<Integer> iList = new ArrayList();
iList = returList();
for (int i = 0; i < iList.size(); i++) {
System.out.println(iList.get(i));
}
}
public static ArrayList returList() {
ArrayList al = new ArrayList();
al.add("S");
al.add(1);
return al;
}
now my query is why the Arraylist is accepting the raw arraylist object creation in line ‘ArrayList iList = new ArrayList();’ and the same case even from the method call return even.
Now, which type of data will be will be there and will Generics implies ? i see no compilation errors and this code is running fine even.
Because of the way Java generics are implemented (see Type Erasure for an introductory explanation) it is possible to create ‘raw’ type instances of generic classes and then cast them to a generic version as in your assignments to
iList. This results in a compiler warning as it is a potentially unsafe operation. You can add any type you like to a raw ArrayList (it’s equivalent to ArrayList) but if you then cast it to a more specific generic type you may have an inconsistent collection.In your example you have created such a list in
returList. However your code doesn’t exhibit this asprintln()doesn’t rely on the type of the list element passed to it. Add a line such asto your
forloop and run your code and you will get aClassCastExceptionas your programme attempts to cast the string"s"to anInteger.When a generic collection is inconsistent you you won’t find out until you try to access the inconsistent elements using the generic type.