How do treemap and TreeSet compare elements when sorting? How does the sort () method in the Collections tool class compare elements?

Source: Internet
Author: User
Tags comparable

TreeSet requires that the class to which the object belongs must implement the comparable interface, which provides the CompareTo () method of the comparison element, which is called back when the element is inserted and the method compares the size of the element. treemap requires that keys stored in a key pair map must implement the comparable interface to sort the elements according to the key. The sort method of the collections tool class has two overloaded forms, the first one requiring the object to be placed in the incoming sorting container to implement the comparable interface for comparing the elements, and the second not mandatory to require that the elements in the container be comparable, but that the second argument is required. The parameter is a subtype of the comparator interface (it is necessary to override the Compare method implementation element comparison), which is equivalent to a temporary defined collation, which is actually an algorithm that injects a comparison element size through an interface, and is also an application of the callback pattern (functional programming in Java).

Example 1:

 Public classStudentImplementsComparable<student> {    PrivateString name;//name    Private intAge//Age     PublicStudent (String name,intAge ) {         This. Name =name;  This. Age =Age ; } @Override PublicString toString () {return"Student [name=" + name + ", age=" + Age + "]"; } @Override Public intcompareTo (Student o) {return  This. age-o.age;//Compare Age (ascending of age)    }}

ImportJava.util.Set;ImportJava.util.TreeSet;classTest01 { Public Static voidMain (string[] args) {Set<Student> set =NewTreeset<> ();//Diamond Syntax for Java 7 (no write type required in angle brackets behind the constructor)Set.add (NewStudent ("Hao LUO", 33)); Set.add (NewStudent ("XJ WANG", 32)); Set.add (NewStudent ("Bruce LEE", 60)); Set.add (NewStudent ("Bob YANG", 22));  for(Student stu:set) {System.out.println (STU); }//Output Result://Student [Name=bob YANG, age=22]//Student [Name=xj WANG, age=32]//Student [Name=hao LUO, age=33]//Student [Name=bruce LEE, age=60]    }}

Example 2:

 Public classStudent {PrivateString name;//name    Private intAge//Age     PublicStudent (String name,intAge ) {         This. Name =name;  This. Age =Age ; }    /*** Get student name*/     PublicString GetName () {returnname; }    /*** Get student Age*/     Public intGetage () {returnAge ; } @Override PublicString toString () {return"Student [name=" + name + ", age=" + Age + "]"; }}

Importjava.util.ArrayList;Importjava.util.Collections;ImportJava.util.Comparator;Importjava.util.List;classTest02 { Public Static voidMain (string[] args) {List<Student> list =NewArraylist<> ();//Diamond Syntax for Java 7 (no write type required in angle brackets behind the constructor)List.add (NewStudent ("Hao LUO", 33)); List.add (NewStudent ("XJ WANG", 32)); List.add (NewStudent ("Bruce LEE", 60)); List.add (NewStudent ("Bob YANG", 22)); //Passing in a comparator interface object by the second parameter of the Sort method//equivalent to passing an algorithm to the size of a comparison object into the Sort method//since there is no concept of function pointers, functor, and delegates in Java//so the only option to pass an algorithm into a method is through an interface callbackCollections.sort (list,NewComparator<student>() {@Override Public intCompare (Student O1, Student O2) {returnO1.getname (). CompareTo (O2.getname ());//Compare student Names            }        });  for(Student stu:list) {System.out.println (STU); }//Output Result://Student [Name=bob YANG, age=22]//Student [Name=bruce LEE, age=60]//Student [Name=hao LUO, age=33]//Student [Name=xj WANG, age=32]    }}

How do treemap and TreeSet compare elements when sorting? How does the sort () method in the Collections tool class compare elements?

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.