Win a copy of Escape Velocity: Better Metrics for Agile Teams this week in the Agile and Other Processes forum!
  • 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
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

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: 76479
366
  • 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.
 
This is my favorite tiny ad:
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic