Tuesday, 3 November 2015

How to work with Subsets of TreeSet

Since a TreeSet is ordered ,a subset of the tree set is also ordered. TreeSet class provides several methods for working with these subsets.The two subsets among them are headSet() and tailSet():

    public SortedSet headSet(Object toElement)  
    public SortedSet tailSet(Object toElement)  

The third method subSet() provides the endpoints:

    public SortedSet subSet(Object fromElement,Object toElement)  

All of these methods will give you a view into the underlying tree such that changes to that view are reflected in the set from which the view came from .In other words, if you remove something from the subset, it's gone. In addition, if you try to add something to the subtree, it must fit within your view of the tree. And if you add something to the original view, the subset will be altered too.

In headSet method, fromElement is not included as a part of resultant set whereas in case of tailSet,fromElement is included.

If you want to include the fromElement in the subset of headSet, you must do something like this

   SortedSet headSet = set.headSet(toElement+"\0");  

and if you don't want to include the fromElement in subset of tailSet:

   SortedSet tailSet = set.tailSet(fromElement+"\0");  

To get a set that includes both the ends, use:

   SortedSet set = set.subSet(fromElement,toElement+"\0");  

Or, for a set that includes neither end, use:

   SortedSet set = set.subSet(fromElement+"\0",toElement);  

Here are some few examples which will help to understand this better.
For example, you have a treeSet ("John","Mary","Dean","Sam","Lillith").as we know tree is ordered set.All the element will stored in sorted order.

  • tailSet("John") :- [John,Lillith,Mary,Sam]
  • headSet("John") :- [Dean]
  • headSet("John\0") :- [Dean,John]
  • tailSet("John\0") :- [Lillith,Mary,Sam]
  • subSet("John","Mary\0") :- [John,Lillith,Mary]
  • subSet("John","John\0") :- [John]
  • subSet("John","John") :- []

Enjoy Reading.

No comments:

Post a Comment