wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Repositioning an object in a TreeSet? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Repositioning an object in a TreeSet?" Watch "Repositioning an object in a TreeSet?" New topic
Author

Repositioning an object in a TreeSet?

Yuriy Zilbergleyt
Ranch Hand

Joined: Dec 13, 2004
Posts: 429
Hi everybody,

I'm assuming that when an object is placed into a TreeSet that uses a custom Comparator, it's position is determined by Comparator.compare(). What if the object property that compare() uses changes after the object is already inserted into the set?

For example I may be keeping a TreeSet of Document objects sorted by their lastAccessedDate, and the lastAccessedDate of an object changes. Is there a way of making the TreeSet aware of this, or should I just remove the Document from the TreeSet before changing the date and reinsert it afterwards?

Thank you,

Yuriy
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Order appears to be determined at insertion. I don't know of a way to "re-order" the TreeSet if elements change.

[ July 27, 2005: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
You could get into something tricky that listens for changes (see Observer and Observable), removes the object and reinserts it. Or you could create a new TreeSet from your existing TreeSet to re-sort everything before you read from it again.


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
 
Don't get me started about those stupid light bulbs.
 
subject: Repositioning an object in a TreeSet?
 
Similar Threads
how to retieve the keys and values from a propertyfile in an order
Plz xplain this code on TreeSet
Doubt in K&B SCJP 5: topic Maps
How to implement Comparable
code