Dark Horse programmer [TreeSet collection], dark horse programmer treeset

Source: Internet
Author: User
Tags sorted by name

Dark Horse programmer [TreeSet collection], dark horse programmer treeset

------- Android training, java training, and hope to communicate with you! ----------

TreeSet set

The TreeSet set is an ordered set implemented by TreeMap. The internal storage elements are automatically sorted by natural order. Therefore, if you want to retain the storage order, you are not recommended to use TreeSet.

TreeSet inherits the Set feature, that is, duplicate elements are not allowed. It compares all elements through the compareTo method. In this method, equal elements are the same elements. In addition, the TreeSet storage element is in the form of a binary tree, which improves the efficiency to a certain extent. The following figure shows the storage principle of TreeSet:

This is the basic principle of the TreeSet storage elements. Next we will use the code to verify whether the values of the elements are arranged in what we call:

 

    public static void main(String[] args) {        // TODO Auto-generated method stub        TreeSet set = new TreeSet();        set.add(24);        set.add(30);        set.add(12);        set.add(16);        set.add(24);        for (Iterator iterator = set.iterator(); iterator.hasNext();) {            System.out.println(iterator.next());                    }    }

Well, the program running results are the same as what we call. They are arranged by natural sorting, so that it is easy to directly arrange numbers or strings, what if we store an object in the collection? Let's take a look at the Code:

Public static void main (String [] args) {TreeSet <Student> set = new TreeSet <Student> (); set. add (new Student ("James", 20); set. add (new Student ("Li Si", 19); set. add (new Student ("Wang Wu", 23); set. add (new Student ("ah", 16); set. add (new Student ("Zhao ", 25); for (Iterator <Student> it = set. iterator (); it. hasNext ();) {Student stu = (Student) it. next (); System. out. println (stu. getName () + stu. getAge ());}}

If you run this Code directly, we will find that it reports a Student cannot be cast to java. lang. comparable error. That is to say, the Student class cannot compare values. We know that numbers can be relatively large, and letters or Chinese characters can be sorted in order. However, if you directly send a class to the TreeSet, he will be confused about what you want him to compare. Then we need to manually give it a comparison scheme, that is, let the Student class implement the compareTo method in the Comparable interface. The return value type of this method is an int type, by viewing the API, we can find that if this method returns 0, the value is the same, if-1 is returned, it is smaller than, if it returns a positive integer, it is greater, now that we know the comparison principle, we can easily implement this method.

Class Student implements Comparable {private String name; private int age; public Student (String name, int age) {this. name = name; this. age = age;} public String getName () {return name;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public void setAge (int age) {this. age = age ;}@ Override public int compareTo (Object o) {if (! (O instanceof Student) {throw new RuntimeErrorException (null, "not a Student object! ");} Student stu = (Student) o; if (stu. getAge ()> this. age) {return 1;} else if (stu. getAge () <this. age) {return-1;} else {return this. name. compareTo (stu. getName ());}}}

In this way, a method of sorting by age is implemented, and if the age is the same, it will be sorted by name. The Object parameter of compareTo indicates the next element in the Set, which needs to be converted before comparison. If it is not the same class, an exception is thrown.

As we mentioned above, the TreeSet set will be compared using the compareTo method. In our program, Student with the same name and age will not be added to the set.

Next we will consider another scenario. For example, the code above in the company has been written by someone else, and we need another sort method, such as sorting by name. What should we do? We cannot modify the code written by others. At this time, we need to implement the compare method through the Comparator interface, and then pass this implementation class to the TreeSet through the constructor, note that the return value of the compare method is still int, and its two parameters are of the Object type, representing the current element and the next element respectively.

Class Comp implements Comparator <Student >{@ Override public int compare (Student o1, Student o2) {return o1.getName (). compareTo (o2.getName () ;}// in the main method, TreeSet <Student> set = new TreeSet <Student> (new Comp ());

In this way, a custom sorting method is implemented.

 

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.