This week's book giveaway is in the Java in General forum.
We're giving away four copies of Think Java: How to Think Like a Computer Scientist and have Allen B. Downey & Chris Mayfield on-line!
See this thread for details.
Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

sortedSet with objects

 
Peter Primrose
Ranch Hand
Posts: 755
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Say I have a list of objects with the following params:

1. Name
2. Age
3. Address

I don't want to have any duplication with the address argument.
Question, using a sortedSet how can I avoid this duplication, so the list will contain eventually only unique addresses?

Thanks
peter
 
Nathaniel Stoddard
Ranch Hand
Posts: 1258
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You will either need to have your class implement Comparable, or pass a Comparator (which you'll write) to the constructor of TreeSet (or whatever implementation you're using for SortedSet).

Check out the API docs for SortedSet for more information.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd lean towards Comparator. If you implement Comparable (and you might want to) it should be compatible with Equals. If you compare on address only for the purpose of duplicates you're saying any two objects with the same address are equal, and that may not be intuitive to future generations of coders who have to maintain the code. A special-purpose comparator would be created and used local to the code that adds objects to the list and would not influence how the objects behave at other times.

Look at the doc for Comparable and Comparator (right after SortedList ) and see if all that makes sense.
 
Peter Primrose
Ranch Hand
Posts: 755
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks, I built the comparator and it works.
so now I have an arraylist that is sorted by address. I need to convert it to the sortedSet what is the best way to do it and make sure no dupp will occur?
 
Nathaniel Stoddard
Ranch Hand
Posts: 1258
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That what Sets are for -- just add all your elements to the Set. It will take care of the rest for you.
 
Peter Primrose
Ranch Hand
Posts: 755
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
got it! it works thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic