Java Collection Framework-treeset

Source: Internet
Author: User

The/*treeset can sort the objects in the set set, and TreeSet calls the comparable interface CompareTo () at the bottom. So, when you use TreeSet to store custom objects, you want to implement the natural ordering of custom class objects, The class is required to implement the comparable interface and overrides the only method CompareTo () that overrides the interface. Requirements: Store custom objects in the TreeSet collection students. Want to sort by the age of the students. Remember: When sorting, when the main conditions are the same, be sure to judge the secondary conditions. In this case, there are two classmates of the same age, if not to judge the secondary condition action, then the student's information is not stored, should be returned when the CompareTo is 0. Therefore, you need to continue to determine whether the name is consistent. The CompareTo method in the comparable interface is also implemented in the String class. Therefore, you can use Str.compareto (STR1) directly to achieve a string comparison. The underlying data structure of the TreeSet is a two-fork tree. The basis for preserving data uniqueness is the first way that the CompareTo method returns 0.TreeSet ordering: to make the elements themselves comparable. The element needs to implement the comparable interface, overriding the CompareTo method. This approach is also called the natural order of the elements, or the default order. TreeSet the second way of ordering: The element itself is not comparable, then the comparator is constructed, and the comparator is passed as a parameter to the constructor of TreeSet with parameters. When both methods are present, the comparator is the main one.!!!!!!!!!!!! The implementation of the two methods is!!!!!!!!!!!!!!!!!! in the program Treesetdemo1.java */import Java.util.*;class Student implements comparable//because TreeSet will naturally sort the saved objects, it actually implements the comparable interface. {Private String name;private int age; Student (String Name,int age) {this.name=name;this.age=age;} Public String GetName () {return name;} public int getage () {return age;} public int compareTo (Object obj)//Overrides the method in the interface to achieve the ability to sort by age. {if (!) ( obj instanceof Student)) throw newRuntimeException ("Not student object"); Student s= (Student) obj; Treesetdemo.sop (this.name+ "..." +s.name);   Treesetdemo.sop (this.name); First, lily_01 comes in and stores it in the TreeSet collection. Then the lily_02 came in and compared to the lily_01. The IF (this.age>s.age)//Bottom call is the CompareTo method. So after lily_02 came in, this is worth lily_02. In plain speaking, whoever comes in this represents who.         return 1;  Large placed on the right of the binary tree if (this.age==s.age) {return this.name.compareTo (s.name); If that's the case, the same object will not be stored.  }return-1; The small is placed on the left side of the binary tree. }}class Treesetdemo {public static void main (string[] args) {TreeSet ts=new TreeSet (); Ts.add (New Student ("lily_01", 10)); Ts.add (New Student ("lily_02", 9)),//ts.add (New Student ("lily_03"),//ts.add (New Student ("lily_04");//ts.add (New Student ("Lily_05", 5)),//ts.add (New Student ("lily_06"),//ts.add (New Student ("lily_07"); Iterator it= Ts.iterator (); while (It.hasnext ()) {Object obj=it.next (); Student s= (Student) Obj;//sop (s.getname () + "..." +s.getage ());} System.out.println ("Hello world!");} public static void Sop (Object obj) {System.out.println (obj);}}
/* Summary, TreeSet can sort the objects in natural order because the underlying data structure is a two-fork tree and implements the CompareTo () method of the comparable interface. The comparable interface is implemented through the class of the custom object, and the CompareTo () method is overridden to store the ordered object data according to its own needs. Returns 1, indicating that the new element is larger and placed on the right child node of the binary tree; Returns-1, indicating that the new element is smaller, placed in the left child node of the binary tree, and returns 0, indicating that the object element is consistent, then comparing other secondary conditions (such as name, compared to age) */import java.util.*; Class Student implements comparable{private String name;private int age; Student (String Name,int age) {this.name=name;this.age=age;} Public String GetName () {return name;} public int getage () {return age;} public int compareTo (Object obj) {/* is sorted by name, and if name is the same, sort by age (ascending) */if (! ( obj instanceof Student)) throw new RuntimeException ("Not student object"); Student s= (Student) obj;int X=this.name.compareto (s.name); if (x==0) {if (this.age>s.age) return 1;if (this.age== S.age) return 0;return-1;} Return x;/* output in the order in which they are entered: return 1;*//* output in reverse order: return-1;*//* stores only one student's information: return 0;*/}}class TreeSetDemo1 {public static void Main (string[] args) {TreeSet ts=new TreeSet ();//Use Method one: By implementing the comparable interface and overwriting the CompareTo () method. TreeSet ts=new TreeSet (New Mycompare ()); Use method Two: Use the comparator to sort the age. Construct a comparator to implement CompaRator interface, and overrides the Compare method. Ts.add (New Student ("Lily")), Ts.add (New Student ("Jhon"), Ts.add (New Student ("Jane")), Ts.add (New Student (" Sara ("Ts.add"); Student ("Demetria"); Ts.add (New Student ("Mike"); Ts.add (New Student ("Lily"); Terator It=ts.iterator (); while (It.hasnext ()) {Student s= (Student) It.next (), SOP (S.getname () + "," +s.getage ());} System.out.println ("Hello world!");} public static void Sop (Object obj) {System.out.println (obj);}} Class Mycompare implements Comparator//defines the comparator, which implements sorting by student age {public int compare (Object obj1,object obj2) {if (! Obj1 instanceof Student) | |! (Obj2 instanceof Student)) throw new RuntimeException ("There is an object that is not of the student type. "); Student s1= (Student) obj1; Student s2= (Student) obj2;if (S1.getage () >s2.getage ()) Return 1;if (S1.getage () ==s2.getage ()) return S1.getname (). CompareTo (S2.getname ()); return-1;}}


Java Collection Framework-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.