Is there any difference between the two TreeSets ?:
Set<String> s = new TreeSet<String>();
SortedSet<String> s = new TreeSet<String>();
Is there any difference between the two TreeSets ?:
Set<String> s = new TreeSet<String>();
SortedSet<String> s = new TreeSet<String>();
Difference is s have acccess to method shared by s type (if you don't cast it). But the object real type is the same.
Calling new HashSet<String>()
will always create an empty HashSet
. While these are all different instances, they are equal, regardless of whether you assign them to a HashSet
, a Set
or even a plain old Object
.
Note, however, that HashSet
is not a SortedSet
, and the second statement in the question will cause a compilation error.
Only their apparent type is different. Since their real type is the same, their behavior will be identical.
It's similar to:
Integer i = 42;
Object o = i;
String s1 = i.toString(); // "42"
String s2 = o.toString(); // "42"