Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding new element to tree also adds it to partial copy of tree

In the following code, we create two distinct TreeSet objects.

We assign some values to 1st object, and then we assign a subset of 1st object to 2nd object. We then add an element (609) to 1st object only. Why then does this new element appear in both objects?

import java.util.*;
public class Explorer1 {
    public static void main(String[] args) {
        TreeSet<Integer> s = new TreeSet<Integer>();
        TreeSet<Integer> subs = new TreeSet<Integer>();
        for(int i = 606; i < 613; i++)
            if(i%2 == 0) s.add(i);
        subs = (TreeSet)s.subSet(608, true, 611, true);
        s.add(609);
        System.out.println(s + " " + subs);
    }
}

Output:[606, 608, 609, 610, 612] [608, 609, 610]

like image 608
Nakul Patekar Avatar asked Mar 23 '23 01:03

Nakul Patekar


1 Answers

The answer is in the documentation:

The returned set is backed by this set, so changes in the returned set are reflected in this set, and vice-versa. The returned set supports all optional set operations that this set supports.

Of course, if you don't want the changes in the returned set to reflect in the original set, just make a copy of subset:

subs = new TreeSet<>(s.subSet(608, true, 611, true));

Note that, your original code has an unchecked cast operation. You should not cast to TreeSet, but TreeSet<Integer>:

subs = (TreeSet<Integer>)s.subSet(608, true, 611, true);
like image 112
Rohit Jain Avatar answered Apr 06 '23 08:04

Rohit Jain