title: Is it OK to have a Java Comparator where order can change dynamically?
body: <p>I have a set of time stamped values I'd like to place in a sorted set.</p>
  
  <pre><code>public class TimedValue {
      public Date time;
      public double value;
  
      public TimedValue(Date time, double value) {
          this.time = time;
          this.value = value;
      }
  }
  </code></pre>
  
  <p>The business logic for sorting this set says that values must be ordered in descending value order, <em>unless it's more than 7 days older than the newest value</em>.</p>
  
  <p>So as a test, I came up with the following code...</p>
  
  <pre><code>DateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy");
  TreeSet&lt;TimedValue&gt; mySet = new TreeSet&lt;TimedValue&gt;(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));
  </code></pre>
  
  <p>As you can see, initially the first value is more relevant than the second, but once the final value is added to the set, the first value has expired and should be the least relevant.</p>
  
  <p>My initial tests say that this should work... that the TreeSet will dynamically reorder the entire list as more values are added.</p>
  
  <p>But even though I see it, I'm not sure I believe it.</p>
  
  <p>Will a sorted collection reorder the entire set as each element is added?  Are there any gotchas to using a sorted collection in this manner (i.e performance)?  Would it be better to manually sort the list after all values have been added (I'm guessing it would be)?</p>
  
  <p><br/><br/>
  <strong>Follow-up:</strong>
  As many (and even I to a certain extent) suspected, the sorted collection does not support this manner of "dynamic reordering".  I believe my initial test was "working" quite by accident.  As I added more elements to the set, the "order" broke down quite rapidly.  Thanks for all the great responses, I refactored my code to use approaches suggested by many of you.</p>