Java in-depth understanding of TreeSet

Source: Internet
Author: User
Tags comparable

The TreeSet in Java is a subclass of set, and the TreeSet collection is used to sort the object elements, as well as to ensure that the elements are unique.
So why does the TreeSet guarantee that the element is unique and how is it sorted? Look at the code first:

 Public Static voidDemo () {TreeSet<Person> ts =NewTreeset<>(); Ts.add (NewPerson ("Zhang San", at)); Ts.add (NewPerson ("John Doe", -)); Ts.add (NewPerson ("Zhou Qi", -)); Ts.add (NewPerson ("Harry", +)); Ts.add (NewPerson ("Zhao Liu", -)); System. out. println (TS); }

Execution Result:

Error, an exception is thrown: Java.lang.ClassCastException obviously a type conversion exception occurred. The reason is that we need to tell treeset how to make the comparison element, and if not specified, throws the exception.


How to resolve:
How to specify the rules for comparison, you need to implement the ' comparable ' interface in the custom class (person) and override the CompareTo method in the interface

 Public classPerson implements Comparable<person> {    PrivateString name; Private intAge ; ...     Public intcompareTo (Person o) {return 0;//when the CompareTo method returns 0, there is only one element in the collection        return 1;//How the collection will be stored when the CompareTo method returns a positive number        return-1;//when the CompareTo method returns a negative number, the collection is stored in reverse    }}

Why is


returning 0, only one element is saved, 1 is stored in reverse, and 1 is returned? The reason is that the treeset is actually a binary tree mechanism, and each insertion of a new element (except the first one) will call the ' CompareTo () ' method to compare with the previous inserted element and arrange it in the structure of the two-fork tree.
1. If the return value of ' compareTo () ' Is dead to 0, the element value is considered to be the same element each time it is compared, then no new element except the first one is inserted into the treeset. So there is only the first element inserted in TreeSet.
2. If the return value of ' compareTo () ' Is dead to 1, the element value is considered to be larger than the previous element each time, so the binary tree is stored with the right side of the root, and the reading is a positive order.
3. If the return value of ' compareTo () ' Is dead to-1, each time the element value is compared, the newly inserted element is considered to be smaller than the previous element, so when the binary tree is stored, there will be the left side of the root, and the reading is in reverse order.

Using the rules above, we can sort by age. Code

 Public int compareTo (Person o) {        int-this. age-o.age;                // age is the main condition        of comparison return 0 this. Name.compareto (o.name): num; // name is a minor condition for comparison    }

Sort by name (depending on the Unicode encoding size), the code is as follows:

 Public int compareTo (Person o) {        int-this. Name.compareto (o.name);        // name is the main condition        return 0 this. age-o.age:num;    // age is a secondary condition    }


Sort by name length, with the following code:

 public  int   CompareTo (person O) { int  length = this . Name.length ()-o.name.length (); //         Comparison length is the primary condition  int  num = length = = 0 ?    this . Name.compareto (o.name): length; //         compare content as secondary condition  return  num = = 0 ?                        this . Age-o.age:num; //  compare Age to secondary condition } 


The above is how TreeSet compares custom objects, so let's take a look at how TreeSet compares elements using comparators.

Requirement: Now you want to make a string comparison of string lengths in TreeSet.

//define a class, implement the comparator interface, and override the Compare () method,classComparebylen/*extends Object*/Implements Comparator<string>{@Override Public intCompare (string s1, string s2) {//compare by length of string        intnum = S1.length ()-s2.length ();//length as the main condition        returnnum = =0? S1.compareto (S2): num;//content is a secondary condition    }}

     Public Static voidDemo4 () {//Requirements: Sort strings by lengthtreeset<string> ts =NewTreeset<> (NewComparebylen ());//Comparator C = new Comparebylen ();Ts.add ("aaaaaaaa"); Ts.add ("Z"); Ts.add ("WC"); Ts.add ("NBA"); Ts.add ("CBA"); System. out. println (TS); }

Summarize
  1. Characteristics
    • TreeSet are used for sorting, you can specify a sequence in which the objects are stored in the order specified
  2. How to use
    • A. Natural order (comparable)
      • The Add () method of the TreeSet class promotes the stored object to the comparable type
      • The CompareTo () method of the calling object and the object comparison in the collection
      • Stored according to the results returned by the CompareTo () method
    • B. Comparator order (Comparator)
      • Create a treeset when you can make a comparator
      • If a subclass object of comparator is passed in, the TreeSet is sorted in the order of the comparator
      • The Add () method internally calls the Compare () method in the comparator interface to sort
      • The object being called is the first parameter of the Compare method, and the object in the collection is the second parameter of the Compare method
    • C. Two different ways of difference
      • TreeSet constructors do not pass anything, by default in the order of comparable in the class (no error ClassCastException)
      • TreeSet if the comparator is passed in, priority is given to comparator
?

Java in-depth understanding of 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.