Can someone explain me why this code compiles and runs fine, despite the fact that SortedSet is an interface and not a concrete class:
public static void main(String[] args) {
Integer[] nums = {4, 7, 8, 14, 45, 33};
List<Integer> numList = Arrays.asList(nums);
TreeSet<Integer> numSet = new TreeSet<Integer>();
numSet.addAll(numList);
SortedSet<Integer> sSet = numSet.subSet(5, 20);
sSet.add(17);
System.out.println(sSet);
}
It prints normally the result: [7, 8, 14, 17]
Furthermore, my wonder is heightened by the fact that the SortedSet cannot be instansiated (expectedly). This line does not compile:
SortedSet<Integer> sSet = new SortedSet<Integer>();
However, if I try the code:
public static void main(String[] args) {
Integer[] nums = {4, 7, 8, 14, 45, 33};
List<Integer> numList = Arrays.asList(nums);
numList.add(56);
System.out.println(numList);
}
it throws an UnsupportedOperationException. I reckon, this comes from the fact that List is an interface and cannot be handled as a concrete class. What is true about SortedSet?
SortedSet is an interface. This means you can have a reference to a class which implements this interface, but not create an instance of class with no implmenetation.
In the case of Arrays.asList() it returns a class which wraps the original array. You cannot add to the original array so add is not supported. If you use set for example, you will alter the original array.