Add a new element to a SortedSet
Posted
by
arjacsoh
on Stack Overflow
See other posts from Stack Overflow
or by arjacsoh
Published on 2012-12-16T10:47:58Z
Indexed on
2012/12/16
11:04 UTC
Read the original article
Hit count: 337
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
?
© Stack Overflow or respective owner