aspose file tools*
The moose likes Java in General and the fly likes sortedSet with objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "sortedSet with objects" Watch "sortedSet with objects" New topic
Author

sortedSet with objects

Peter Primrose
Ranch Hand

Joined: Sep 10, 2004
Posts: 755
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

Joined: May 29, 2003
Posts: 1258
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.


Nathaniel Stodard<br />SCJP, SCJD, SCWCD, SCBCD, SCDJWS, ICAD, ICSD, ICED
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
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.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Peter Primrose
Ranch Hand

Joined: Sep 10, 2004
Posts: 755
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

Joined: May 29, 2003
Posts: 1258
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

Joined: Sep 10, 2004
Posts: 755
got it! it works thanks
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: sortedSet with objects