Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working of Treeset

Tags:

java

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.

like image 368
Sandeep Rao Avatar asked Dec 31 '25 05:12

Sandeep Rao


2 Answers

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.

like image 176
Todd Avatar answered Jan 02 '26 17:01

Todd


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.

like image 38
yshavit Avatar answered Jan 02 '26 17:01

yshavit