Sandeep Rao
Sandeep Rao

Reputation: 1757

Working of Treeset

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.

Upvotes: 3

Views: 3505

Answers (4)

yshavit
yshavit

Reputation: 43436

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.

Upvotes: 1

Todd
Todd

Reputation: 31720

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.

Upvotes: 3

st0le
st0le

Reputation: 33565

If you look carefully over the documentation of TreeSet

subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)
Returns a view of the portion of this set whose elements range from fromElement to toElement.

Note, it returns a "View" as in a reference into the original set. s not distinct from the subs only it's contents are filtered.

Upvotes: 1

Aravind Yarram
Aravind Yarram

Reputation: 80192

The subset just returns a VIEW of the original set and since sets are ordered the 609 added qualifies for the ranges you have given.

Read more about it here.

Upvotes: 1

Related Questions