I have a set of timestamped values that I would like to place in a sorted set.
public class TimedValue { public Date time; public double value; public TimedValue(Date time, double value) { this.time = time; this.value = value; } }
The business logic for sorting this set indicates that the values should be ordered in descending order of value if it does not exceed 7 days than the newest.
So, as a test, I came up with the following code ...
DateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy"); TreeSet<TimedValue> mySet = new TreeSet<TimedValue>(new DateAwareComparator()); mySet.add(new TimedValue(dateFormatter.parse("01/01/2009"), 4.0 )); // too old mySet.add(new TimedValue(dateFormatter.parse("01/03/2009"), 3.0)); // Most relevant mySet.add(new TimedValue(dateFormatter.parse("01/09/2009"), 2.0));
As you can see, initially the first value is more relevant than the second, but after the final value is added to the set, the first value has expired and should be the least relevant.
My initial tests say this should work ... that TreeSet will dynamically reorder the entire list as more values are added.
But even if I see it, I'm not sure I believe in it.
Will a sorted collection reorder the entire set as each item is added? Are there any problems using a sorted collection this way (e.g. performance)? Would it be better to manually sort the list after all the values have been added (I assume it will)?
Subsequent: Many people (and even me to some extent) believe that a sorted collection does not support this "dynamic reordering" method. I believe that my initial test was "working" completely by accident. When I added more elements to the set, the "order" broke pretty quickly. Thanks for all the great answers, I reorganized my code to use the approaches suggested by many of you.