2

Is there any difference between the two TreeSets ?:

Set<String> s = new TreeSet<String>();
SortedSet<String> s = new TreeSet<String>();
bluesony
  • 459
  • 1
  • 5
  • 28
  • 2
    The second one won't compile. – SLaks Jan 29 '17 at 15:01
  • Don't confuse static/compile time and dynamic/runtime types. – duffymo Jan 29 '17 at 15:02
  • You're essentially asking about the difference between a variable's type and its referred to object's type. – Hovercraft Full Of Eels Jan 29 '17 at 15:06
  • @bluesony I might vote to reopen if you edit your Question for clarity and add some explanation. Your use of the variable named `s` in both lines of code creates some ambiguity about your intentions. Are you confused about re-using/recycling a variable’s name? Or are you confused about assigning a concrete class `TreeSet` to either of two interfaces (`Set`, `SortedSet`)? If the latter, then your Question is *not* a duplicate of the linked Question. Your title suggests the latter, but some more explanation is due. – Basil Bourque Jan 29 '17 at 21:38

3 Answers3

2

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.

busz
  • 86
  • 2
  • You are correct, thank you. If I try s.first() for the first TreeSet, it will throw a compilation error: cannot find symbol method first(). Instead it compiles and runs just fine with the second TreeSet – bluesony Jan 29 '17 at 15:36
0

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
-2

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"
rom1v
  • 2,752
  • 3
  • 21
  • 47
  • Your code example is entirely irrelevant. The `toString` method generates a separate and distinct object unrelated to the original `Object` named `o`. – Basil Bourque Jan 29 '17 at 17:59
  • @BasilBourque It highlights that the behavior of `toString()` is the same whatever the _apparent_ type is. I just added a line to make it more explicit. Yeah, that's trivial, but IMO it answers to the question… – rom1v Jan 29 '17 at 18:10