I java 6 i can declare the arraylist as follows
Way1: using generics i.e <Integer>
on right hand side too
List<Integer> p = new ArrayList<Integer>();
Way2: using the diamond operator
List<Integer> p = new ArrayList<>();
Way3: using generic only at left side
List<Integer> p = new ArrayList();
I prefer to use way 3 as its brief. Is there any difference between these ways? Which one we should prefer and why?
Update:- I know in java 7 second way is recommended but my question is in context of java 6. Which one is preferable?
To me, way 3 also says p is an arraylist of integers (same conveyed by way1). So I find no difference except the fact IDE displays warning message:
ArrayList is a raw type. References to generic type
ArrayList<E>
should be parameterized
As has been pointed out, Way 2 isn't valid in 1.6. So the question is, is there any difference between Way 1 and Way 3. Apart from readability, no.
Take this code:
Compile it and look at the bytecode using
javap -c
We can see that the exact same bytecode is produced in both cases. Note that as Generics aren't baked in the compiler throws away the information after checking it at compile time and adds in
checkcast
instructions to make sure the casts it does when retrieving objects are safe.