Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Repositioning an object in a TreeSet?

 
Yuriy Zilbergleyt
Ranch Hand
Posts: 429
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic