I have a question about using generics with collections.
ArrayList<Integer> al=new ArrayList<Integer>();
We know that the above line means that ArrayList al is restricted to hold only integers. So the following line gives a compilation error:
al.add("wwww");
But I don’t understand what the below line means,
ArrayList al=new ArrayList<Integer>();
Where we don’t give ArrayList<Integer> at the left side while declaring. Now the following line doesn’t give a compilation error:
al.add("wwww");
So if I declare like
ArrayList al=new ArrayList<Integer>();
that means a1 can accept any types?
What’s the difference between those two declarations?
With this code:
the compiler will generate a warning (which you should heed!) but the code will run without error. The problem comes on extracting data from
a1. If you “know” that it containsIntegervalues, you can just do this:But when you hit the
"www"element you’re going to get aClassCastException. Generics are meant to move such errors to compile time instead of forcing the poor developer to track down how aStringvalue ended up in thatIntegerarray list.