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]
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With