• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

SortedSet declaration

 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

What is the difference between these two declarations. I was looking at samples online and I see samples with declaration #1 below.

Why can't I declare like #2 below? What is the difference between those 2 declarations?

1. SortedSet<String> aSortedSet = new TreeSet<String>() ;

2. TreeSet<String> aTreeset = new TreeSet<String>();

Thanks
nath
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The first means you are programming to the interface rather than an implementation. You can change the TreeSet for anither kind of sorted set if you wish more easily.
 
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
TreeSet implements SortedSet. If you declare a variable to be a TreeSet then it can potentially be difficult to change its runtime type later, but if you declare it to be a SortedSet then you are free to change to another SortedSet implementation without any of your code caring about the change.

This is called programming to interfaces, not implementations.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic