TreeSet () detailed

Source: Internet
Author: User
Tags comparable

/*
* TreeSet can be sorted when storing objects, but it is necessary to specify an algorithm for sorting
*
* Integer can be sorted (with default order), string can be sorted (with default order), the custom class is stored with an exception (no order)
*
* If you want to sort the objects of a custom class into TreeSet, you must implement the comparable interface
* Implement comparable on the class
* Override CompareTo () method
* Define the comparison algorithm within the method, return positive negative numbers or 0 depending on the size relationship
* When using TreeSet to store objects, the Add () method automatically calls the CompareTo () method for comparison, and is stored using a two-fork tree as the result of the comparison.
*/

2.TreeSet relies on treemap to achieve this.
TreeSet is an ordered set, and the elements in the TreeSet are arranged in ascending order, by default, by natural ordering, meaning that the elements in treeset implement comparable interfaces. Or there is a custom comparer.
We can pass a comparer object that implements the comparator interface when constructing a TreeSet object.

Import Java.util.iterator;import java.util.*;p ublic class Treesettest {public    static void Main (string[] args) {        Set ts = new TreeSet ();        Ts.add ("abc");        Ts.add ("xyz");        Ts.add ("rst");        Iterator it = Ts.iterator ();        while (It.hasnext ()) {            System.out.println (It.next ());}}}    

Output Result:

Abc

Rst

Xyz

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.

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.

Package Test.treeset;import Java.util.iterator;import Java.util.set;import java.util.treeset;public class Test_ TreeSet {@SuppressWarnings ("unchecked") public static void main (string[] args) {Set ts = new TreeSet ()            ;            Ts.add (New Teacher ("Zhangsan", 1));            Ts.add (New Teacher ("Lisi", 2));            Ts.add (New Teacher ("Wangmazi", 3));            Ts.add (New Teacher ("Wangwu", 4));            Ts.add (New Teacher ("Mazi", 3));            Iterator it = Ts.iterator ();            while (It.hasnext ()) {System.out.println (It.next ());    }}}class Teacher implements comparable {int num;    String name;        Teacher (String name, int num) {this.num = num;    THIS.name = name;    } public String toString () {return "study number:" + num + "\t\t name:" + name;        }//o nodes in the red and black binary tree, starting from the root node to compare public int compareTo (Object o) {Teacher ss = (Teacher) o; int result = num < Ss.num? 1: (num = = ss.num? 0:-1);//descending//int result = num > ss.num?        1: (num = = ss.num? 0:-1);//Ascending if (result = = 0) {result = Name.compareto (ss.name);    } return result; }}

Operation Result:

School Number: 4 Name: Wangwu
School Number: 3 Name: Mazi
School Number: 3 Name: Wangmazi
School Number: 2 Name: Lisi
School Number: 1 Name: Zhangsan

3. Comparator

You can pass a comparer when you use arrays to sort the elements in an array.

You can pass a comparer when you use collections to sort the elements in the collection.

Can you pass in a comparer when you use TreeSet to sort the elements that are added to them?

  Public TreeSet (COMPARATOR<, Super e> Comparator) {This        (new treemap<e,object> (Comparator));    }

By looking at how it is constructed, you know that you can pass in 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.

Package Test.treeset;import Java.util.comparator;import Java.util.iterator;import Java.util.treeset;public class treesettest {@SuppressWarnings ("unchecked") public static void main (string[] args) {TreeSet ts = new Treese        T (new Teacher2.teachercompare ());        Ts.add (New Teacher2 ("Zhangsan", 2));        Ts.add (New Teacher2 ("Lisi", 1));        Ts.add (New Teacher2 ("Wangmazi", 3));        Ts.add (New Teacher2 ("Mazi", 3));        Iterator it = Ts.iterator ();        while (It.hasnext ()) {System.out.println (It.next ());    }}}class Teacher2 {int num;    String name;        Teacher2 (String name, int num) {this.num = num;    THIS.name = name;    } public String toString () {return ' study number: ' + num + ' name: ' + name; } Static class Teachercompare implements Comparator {//The teacher comes with a comparator//o1 stored in the target node//o2 in the red and black binary tree nodes, from the root node open        Start comparing public int Compare (object O1, Object O2) {Teacher2 S1 = (Teacher2) o1;//transformation    Teacher2 s2 = (Teacher2) o2;//transformation int result = S1.num > s2.num?            1: (S1.num = = s2.num? 0:-1);            if (result = = 0) {result = S1.name.compareTo (s2.name);        } return result; }    }}

Operation Result:

School Number: 1 Name: Lisi
School Number: 2 Name: Zhangsan
School Number: 3 Name: Mazi
School Number: 3 Name: Wangmazi

TreeSet () detailed

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.