What is reason behind supporting the syntax below on java 1.7
List<Integer> ints=new ArrayList<>();
What flexibility does it provide?
If we wanted ints to be of a different type we would explicitly cast it and it would throw an error if the conversion could not be performed.
I am also not clear on how exactly does this work.Since List is an interface how are we able to call a method on it
List<Integer> ints = Arrays.asList(1,2);
ints.get(1);
Since return type of asList() is static<T> List<T> it’s okay to access a field of a static interface without any class providing an implementation of it.But how are we able to access a method on such an interface
The collections library has a lot of them like Collections.Sort()
Who provides the implementation of these methods?
Question 1
Using
instead of
doesn’t add any flexibility as they’re exactly equivalent. The diamond (
<>) indicates that we don’t want the raw type but the obvious parameterized type.Oracle describes it here :
It just makes the code a little less verbose, thus easier to read and maintain. This is probably more evident on Oracle’s example :
compared to
Question 2
Arrays.asList(1,2);returns an object from a concrete class implementing the List interface.In Java 1.6, it’s an instance of the fixed-size
java.util.Arrays.ArrayList:but the important point is that an object always is of a concrete class implementing the methods its interfaces defines.
When you’re doing
Collections.sort(, you’re not using theCollectioninterface but the Collections class which contains this very concrete code :