Monday, February 11, 2013

TreeSet subset detail

When manipulating a subSet of a TreeSet, you need to know that the subSet is linked to the original set, which means that if changes are performed in the original set, they will also get reflected in the subSet, and vice-versa.

public static void main ( String args [ ] ) {
  TreeSet t = new TreeSet();
  t.add(1);
  t.add(2);
  t.add(4);
  TreeSet t2 = (TreeSet)t.subSet(2, true, 4, true);
  t.add(3);
  System.out.print(t + " " + t2);
}


This will print:
[1, 2, 3, 4] [2, 3, 4]

But if you do this:
public static void main ( String args [ ] ) {
  TreeSet t = new TreeSet();
  t.add(1);
  t.add(2);
  t.add(4);
  TreeSet t2 = (TreeSet)t.subSet(2, true, 4, true);
  t.add(5);
  System.out.print(t + " " + t2);
}


It will print:
[1, 2, 4, 5] [2, 4]

because the number 5 is out of range of the subset.

No comments:

Post a Comment