L
Larry Coon
If I build a SortedSet, and later change one of the elements in
the set so that the set should sort differently, how can I get
the SortedSet to re-order itself? Here's an example to illustrate
the issue:
import java.util.*;
public class Test {
public static void main(String[] args) {
SortedSet s = new TreeSet();
// Add nodes non-alphabetically to prove that the tree
// is built correctly.
s.add(new Thing("Third"));
s.add(new Thing("Second"));
s.add(new Thing("First"));
// The tree is initially in alphabetical order.
System.out.println("Original order: " + s);
// Change last element so it should sort differently.
((Thing) s.last()).setString("Fourth");
// I want the SortedSet to be ordered correctly, reflecting
// the change above. Note that the ordering hasn't changed
// even though "Third" is now "Fourth".
System.out.println("New order: " + s);
// Constructing a new SortedSet doesn't work.
SortedSet s2 = new TreeSet(s);
System.out.println("New set: " + s2);
}
}
class Thing implements Comparable {
private String string;
public Thing(String string) {setString(string); }
public void setString(String string) { this.string = string; }
public String toString() { return string; }
public int compareTo(Object o) {
return string.compareTo(((Thing) o).toString());
}
}
the set so that the set should sort differently, how can I get
the SortedSet to re-order itself? Here's an example to illustrate
the issue:
import java.util.*;
public class Test {
public static void main(String[] args) {
SortedSet s = new TreeSet();
// Add nodes non-alphabetically to prove that the tree
// is built correctly.
s.add(new Thing("Third"));
s.add(new Thing("Second"));
s.add(new Thing("First"));
// The tree is initially in alphabetical order.
System.out.println("Original order: " + s);
// Change last element so it should sort differently.
((Thing) s.last()).setString("Fourth");
// I want the SortedSet to be ordered correctly, reflecting
// the change above. Note that the ordering hasn't changed
// even though "Third" is now "Fourth".
System.out.println("New order: " + s);
// Constructing a new SortedSet doesn't work.
SortedSet s2 = new TreeSet(s);
System.out.println("New set: " + s2);
}
}
class Thing implements Comparable {
private String string;
public Thing(String string) {setString(string); }
public void setString(String string) { this.string = string; }
public String toString() { return string; }
public int compareTo(Object o) {
return string.compareTo(((Thing) o).toString());
}
}