Ayushi Kulshreshtha
Ayushi Kulshreshtha

Reputation: 1

How to solve this Treeset program?

This is a java question. I just want to ask why is 9 added to the original list ts also?

class Test {
    public static void main(String args[]){
      TreeSet<Integer> ts=new TreeSet<Integer>();
      ts.add(1);
      ts.add(8);
      ts.add(6);
      ts.add(4);
      SortedSet<Integer> ss = ts.subSet(2, 10);
      ss.add(9);
      System.out.println(ts);
      System.out.println(ss);
  }
}

Please help!

Upvotes: 0

Views: 49

Answers (1)

Jb31
Jb31

Reputation: 1391

As Alowaniak stated in the comments, subset returns only a view of the original set, so changes are reflected to both sets. The JavaDoc says:

The returned set is backed by this set, so changes in the returned set are reflected in this set, and vice-versa.

You could, for example, create a new set based on the subset:

Set<Integer> ss = new TreeSet<Integer>(ts.subSet(2, 10));

to prevent this behavior.

Upvotes: 2

Related Questions