Java Collection (6): TreeSet

Source: Internet
Author: User
Tags addall comparable int size

I. TreeSet INTRODUCTION

Like HashSet is based on the HashMap implementation, TreeSet is based on the TREEMAP implementation. TreeSet is an ordered set, the elements in the TreeSet will be sorted in ascending order, the default is to sort by natural order, integer can be sorted (with default order), string can be sorted (with default order), if you want to put the custom class object into TreeSet to sort, Then the comparable interface must be implemented. Or there is a custom comparer. We can pass a comparer object that implements the comparator interface when constructing a TreeSet object.

The inheritance relationship of 1.TreeSet
public class Treeset<e> extends abstractset<e>    implements Navigableset<e>, Cloneable, Java.io.Serializable
The class diagram relationships of the 2.TreeSet are as follows:

Through the source code we know that treeset inherit from the Abstractset, the implementation of Navigableset, cloneable, serializable interface. Where Abstractset provides a backbone implementation of the Set interface, minimizing the work required to implement this interface. Navigableset is an extended SortedSet with a navigation method that reports the closest match to a given search target, which means that it supports a range of navigation methods. For example, find the most matching item to the specified target. Cloneable supports cloning, Serializable supports serialization.

Two. TreeSet source code parsing 1. Private properties
1 Private transient Navigablemap<e,object> m; 2         3 // present will be constructed as a key value pair for map value and key 4 Private Static Final New Object ();
How to construct 2.TreeSet
1 //default construction method, sorted according to the natural order of its elements2  PublicTreeSet () {3      This(NewTreemap<e,object>());4 }5 6 //constructs a new TreeSet that contains the specified collection element, sorted according to the natural order of its elements. 7  PublicTreeSet (comparator<?SuperE>comparator) {8          This(NewTreemap<>(Comparator));9 }Ten  One //constructs a new empty TreeSet that is sorted according to the specified comparer.  A  PublicTreeSet (collection<?extendsE>c) { -      This(); - AddAll (c); the } -  - //constructs a new TreeSet that has the same mapping and the same ordering as the specified ordered set.  -  PublicTreeSet (sortedset<e>s) { +      This(S.comparator ()); - AddAll (s); + } A  atTreeSet (navigablemap<e,object>m) { -      This. m =m; -}
3. Other Methods 3.1 add

Public boolean Add (E E)

Adds the specified element to this set (if the element does not already exist in the set).

3.2 AddAll

public boolean addall (collection<? extends e> c)

Adds all the elements in the specified collection to this set.

3.3 Remove

public boolean remove (Object o)

Removes the specified element from the set (if the element exists in this set).

3.4 Clear

public void Clear ()

Remove all elements from this set.

3.5 Clone

Public Object Clone ()

Returns a shallow copy of the TreeSet instance. belongs to a shallow copy.

3.6 size

public int size ()

Returns the number of elements in the set (capacity of Set).

3.7 IsEmpty

public boolean isEmpty ()

Returns True if this set contains no elements.

3.8 Comparator

Public comparator<? Super E> Comparator ()

Returns a comparer that sorts the elements in this set, or null if the set uses the natural order of its elements.

3.9 contains

Public Boolean contains (Object o)

Returns True if this set contains the specified element.

3.10 Iterator

Public iterator<e> Iterator ()

Returns an iterator that iterates in ascending order on the elements in this set.

3.11 First

Public E First ()

Returns the current first (lowest) element in this set.

3.12 Last

Public E Last ()

Returns the current last (highest) element in this set.

3.13 Higher

Public e higher (e e)

Returns the smallest element in this set that is strictly greater than the given element, or null if no such element exists.

3.14 Lower

Public e Lower (e e)

Returns the largest element in this set that is strictly less than the given element, or null if no such element exists.

3.15 ceiling

Public e ceiling (e e)

Returns the smallest element in this set that is greater than or equal to the given element, or null if no such element exists.

3.16 Floor

Public e floor (e e)

Returns the largest element in this set that is less than or equal to the given element, or null if no such element exists.

There are some other methods, too many, here do not write, are quickly written in Chinese API, above these are some of the more commonly used methods, other methods used to check the source bar.

three. TreeSet Use examplesorting of 1.String classes

1  Public classTreesettest {2      Public Static voidMain (string[] args) {3Set ts =NewTreeSet ();4Ts.add ("abc"));5Ts.add ("XYZ");6Ts.add ("rst");7Iterator it =ts.iterator ();8          while(It.hasnext ()) {9 System.out.println (It.next ());Ten         } One     } A}
Output Result: abcrstxyz

The printed result is not the same as the order in which it was previously added, it is sorted by a single letter sorting method. This is because the string class implements the comparable interface.

2. Sorting of custom classes

If the object of a class that we define ourselves is to be added to the TreeSet, then this class must implement the comparable interface.

1  Public classTest_treeset {2@SuppressWarnings ("Unchecked")3      Public Static voidMain (string[] args) {4Set ts =NewTreeSet ();5Ts.add (NewTeacher ("Zhangsan", 1));6Ts.add (NewTeacher ("Lisi", 2));7Ts.add (NewTeacher ("Wangmazi", 3));8Ts.add (NewTeacher ("Wangwu", 4));9Ts.add (NewTeacher ("Mazi", 3));TenIterator it =ts.iterator (); One              while(It.hasnext ()) { A System.out.println (It.next ()); -             } -         } the } - classTeacherImplementsComparable { -     intnum; - String name; +  -Teacher (String name,intnum) { +          This. num =num; A          This. Name =name; at     } -  -      PublicString toString () { -         return"School Number:" + num + "\t\t Name:" +name; -     } -  in     //o nodes in the red and black binary tree at the time of storage, starting from the root node comparison -      Public intcompareTo (Object o) { toTeacher SS =(Teacher) o; +         intresult = num < Ss.num? 1: (num = = ss.num? 0:-1);//Descending -         //int result = num > ss.num? 1: (num = = ss.num? 0:-1);//Ascending the         if(Result = = 0) { *result =Name.compareto (ss.name); $         }Panax Notoginseng         returnresult; -     } the}
Operation Result: study Number:4 Name: WANGWU No.:3     Name: Mazi No.:3     Name: Wangmazi No.:2     Name: Lisi No.:1    Name: Zhangsan

NOTE: if int result = num > ss.num? 1: (num = = ss.num? 0:-1); write int result = ss.num > num? 1: (ss.num = = num 0:-1); Then the result is a reverse order, not ascending.

3. Comparator

When you use TreeSet to sort the elements that are added to them, you can sort the elements in the array and collections the elements in the collection as if they were arrays, passing a comparer.

Constructs a new empty treeset that is sorted according to the specified comparer. All elements inserted into the set must be able to be compared by the specified comparer: for any two elements in the set E1 and E2, the execution Comparator.compare (E1, E2) should not throw classcastexception. If the user attempts to add an element that violates this constraint to the set, the add call throws ClassCastException.

1 classTeacher {2     intnum;3 String name;4 5Teacher (String name,intnum) {6          This. num =num;7          This. Name =name;8     }9     Ten      PublicString toString () { One         return"School Number:" + num + "Name:" +name; A     } -  -     Static classTeachercompareImplementsComparator {//a comparator that the teacher comes with the          Public intCompare (Object O1, Object O2) { -Teacher S1 = (Teacher) O1;//Transformation -Teacher s2 = (Teacher) O2;//Transformation -             intresult = s1.num > s2.num? 1: (S1.num = = s2.num? 0:1); +             if(Result = = 0) { -result =S1.name.compareTo (s2.name); +             } A             returnresult; at         } -     } -}
Operation Result: study number:1 Name: Lisi No.:2 Name: Zhangsan No.:3 Name: Mazi No.:3 Name: Wangmazi

Reference: http://cmsblogs.com/?p=1162

Http://www.cnblogs.com/meng72ndsc/archive/2010/12/23/1914477.html

Java Collection (6): TreeSet

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.