This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

SortedSet declaration  RSS feed

 
narendra nath
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • 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
 
Campbell Ritchie
Marshal
Posts: 55672
161
  • Mark post as helpful
  • send pies
  • 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.
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!