How TreeSet performs Automatic Sorting

Source: Internet
Author: User

Today, I learned a piece of code about the automatic sorting function through treeSet, and I 've been tossing for a long time.

There are always some doubts. The subsequent communication and debugging can explain the basic principles of Automatic Sorting:

Automatic Sorting can be achieved in two ways:

One type:

Package xyxysjxy. io; import java. io. bufferedReader; import java. io. bufferedWriter; import java. io. fileWriter; import java. io. IOException; import java. io. inputStreamReader; import java. util. comparator; import java. util. iterator; import java. util. set; import java. util. treeSet; public class StudentInfoImport {public static void main (String [] args) throws IOException {BufferedWriter bw = new BufferedWriter (new FileWriter ("f: \ student.txt"); Set
 
  
Ss = StudentTools. getStudent (); Iterator
  
   
Is = ss. iterator (); while (is. hasNext () {Student student = (Student) is. next (); bw. write (student. toString (); bw. newLine (); bw. flush ();} bw. close () ;}} class Student {private String name; private int cn; private int math; private int en; private int sum; public String getName () {return name ;} public void setName (String name) {this. name = name;} public int getCn () {return cn;} public void setCn (int cn) {this.cn = Cn;} public int getMath () {return math;} public void setMath (int math) {this. math = math;} public int getEn () {return en;} public void setEn (int en) {this. en = en;} public int getSum () {return sum;} public void setSum (int sum) {this. sum = sum;} public Student (String name, int... is) {this. name = name; this.cn = is [0]; this. math = is [1]; this. en = is [2]; this. sum = cn + math + en;} @ Overridepublic String toStr Ing () {return "[name =" + name + "\ tcn =" + cn + "\ tmath =" + math + "\ ten =" + en + "\ tsum =" + sum + "]";} @ Overridepublic boolean equals (Object obj) {if (! (Obj instanceof Student) throw new ClassCastException ("unforced conversion"); Student s = (Student) obj; return s. name. equals (this. name) & s. sum = s. sum ;}@ Overridepublic int hashCode () {return sum * 78 + name. hashCode () ;}} class StudentTools {static Comparator
   
    
Com = new Comparator
    
     
() {@ Overridepublic int compare (Student o1, Student o2) {int sum = new Integer (o1.getSum ()). compareTo (new Integer (o2.getSum (); if (sum = 0) return o1.getName (). compareTo (o2.getName (); return sum ;}}; public static Set
     
      
GetStudent () throws IOException {return getStudent (com);} public static Set
      
        GetStudent (Comparator
       
         Com) throws IOException {Set
        
          StudentSet = null; if (com = null) studentSet = new TreeSet
         
           (); ElsestudentSet = new TreeSet
          
            (Com); BufferedReader br = new BufferedReader (new InputStreamReader (System. in); String len = ""; while (len = br. readLine ())! = Null) {if (len. equals ("over") break; String [] studentInfo = len. split (","); Student s = new Student (studentInfo [0], new int [] {Integer. parseInt (studentInfo [1]), Integer. parseInt (studentInfo [2]), Integer. parseInt (studentInfo [3])}); // when you add data to a HashSet, it will find the added object to implement the Comparable interface, studentSet. add (s) ;}return studentSet ;}}
          
         
        
       
      
     
    
   
  
 

Two types:

Package xyxysjxy. io; import java. io. bufferedReader; import java. io. bufferedWriter; import java. io. fileWriter; import java. io. IOException; import java. io. inputStreamReader; import java. util. comparator; import java. util. iterator; import java. util. set; import java. util. treeSet; public class StudentInfoImport {public static void main (String [] args) throws IOException {BufferedWriter bw = new BufferedWriter (new FileWriter ("f: \ student.txt"); Set
 
  
Ss = StudentTools. getStudent (); Iterator
  
   
Is = ss. iterator (); while (is. hasNext () {Student student = (Student) is. next (); bw. write (student. toString (); bw. newLine (); bw. flush ();} bw. close () ;}} class Student implements Comparable
   
    
{Private String name; private int cn; private int math; private int en; private int sum; public Student (String name, int... is) {this. name = name; this.cn = is [0]; this. math = is [1]; this. en = is [2]; this. sum = cn + math + en;} @ Overridepublic String toString () {return "[name =" + name + "\ tcn =" + cn + "\ tmath =" + math + "\ ten =" + en + "\ tsum =" + sum + "]";} @ Overridepublic boolean equals (Object obj) {if (! (Obj instanceof Student) throw new ClassCastException ("unforced conversion"); Student s = (Student) obj; return s. name. equals (this. name) & s. sum = s. sum;} public int compareTo (Student o) {int sum = new Integer (this. sum ). compareTo (new Integer (o. sum); if (sum = 0) return this. name. compareTo (o. name); return sum ;}@ Overridepublic int hashCode () {return sum * 78 + name. hashCode () ;}} class StudentTools {public static Set
    
     
GetStudent () throws IOException {return getStudent (null);} public static Set
     
      
GetStudent (Comparator
      
        Com) throws IOException {Set
       
         StudentSet = null; if (com = null) studentSet = new TreeSet
        
          (); ElsestudentSet = new TreeSet
         
           (Com); BufferedReader br = new BufferedReader (new InputStreamReader (System. in); String len = ""; while (len = br. readLine ())! = Null) {if (len. equals ("over") break; String [] studentInfo = len. split (","); Student s = new Student (studentInfo [0], new int [] {Integer. parseInt (studentInfo [1]), Integer. parseInt (studentInfo [2]), Integer. parseInt (studentInfo [3])});
          
// When adding data to the HashSet, he will find the added object to implement the Comparable interface, studentSet. add (s) ;}return studentSet ;}}

Use the above two sections of code to explain the execution process:
          

Step 1: receive the value from the console and encapsulate it into a student object.

In fact, a TreeMap object is encapsulated in the treeSet.

When you call the ADD method, you actually call the put method.

 
While (len = br. readLine ())! = Null) {if (len. equals ("over") break; String [] studentInfo = len. split (","); Student s = new Student (studentInfo [0], new int [] {Integer. parseInt (studentInfo [1]), Integer. parseInt (studentInfo [2]), Integer. parseInt (studentInfo [3])});
// When adding data to a HashSet, he will find the added object to implement the Comparable interface, studentSet. add (s);} return studentSet; public TreeSet (Comparator
             Comparator) {this (new TreeMap <> (comparator ));}




Step 2: First, check.

This three-object Operator means this:

First, it judges whether you pass a comparator to the new treeset.

Object. If it is passed, you can directly call the object you passed in.

But if you didn't pass in, then he will perform a type check,

The purpose of the check is to check whether you have implemented Comparable. If so, you can call your own method for implementing the interface.

Public V put (K key, V value) {Entry
              
               
T = root; if (t = null) {compare (key, key); // type (and possibly null) check (L type check) root = new Entry <> (key, value, null); size = 1; modCount ++; return null;} // when the object is stored for the first time, compared with itself, compare (key, key) final int compare (Object k1, Object k2) {return comparator = null? (Comparable
               ) K1). compareTo (K) k2): comparator. compare (K) k1, (K) k2 );}
              



Step 3: When you check whether you have implemented the compare interface or passed a compator object,

It will call your own implementation methods for comparison.

Return values:-, 1 to determine whether the values you are about to take and the size in the treeset are automatically sorted.







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.