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);
}
}
O/P: [606, 608, 609, 610, 612] [608, 609, 610]
Can any explain why 609 is getting added to subs as it is added after assigning to object.
From the JavaDoc for TreeSet...
Returns a view of the portion of this set whose elements range from fromElement to toElement. If fromElement and toElement are equal, the returned set is empty unless fromExclusive and toExclusive are both true. 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.
So when you do s.subSet(), you are really just getting a view on s, not a brand new TreeSet. Any changes you make to set s are reflected in the subset view.
The javadocs for TreeSet say:
Returns a view of the portion of this set whose elements range from fromElement to toElement. If fromElement and toElement are equal, the returned set is empty unless fromExclusive and toExclusive are both true. 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.
(emphasis added)
So, 609 is being added to subs because it's being added to s, which is backed by subs.
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