TreeSet sort, store your own definition object, and define your own example of the comparison device demo

Source: Internet
Author: User
Tags comparable

Set: Unordered. Can not repeat elements.
|--hashset: Data structure is a hash table. The thread is unsynchronized.


The principle of guaranteeing element uniqueness is to infer whether the hashcode value of an element is the same.


Assuming the same, the Equals method of the element continues to be inferred. Is true.



|--treeset: The ability to sort elements in a set collection.


The underlying data structure is a two-fork tree.
The basis for guaranteeing element uniqueness: The CompareTo method return 0.

TreeSet the first way to sort: to make the elements themselves comparable.


Elements need to implement comparable interfaces, overriding CompareTo methods.


Also kinds of ways become the natural order of the elements. Or it's called the default order.

Another way to sort treeset.
When the element itself does not have a comparative nature. Or the comparability that you have is not what you need.


At this point you need to make the collection itself comparable.

At the time of the collection initialization. There's a way of comparing it.


Demo Sample: Requirements:
store your own definition objects in the TreeSet collection students are sorted according to the age of the students .

Package Tan;import Java.util.iterator;import Java.util.treeset;public class Treesetdemo {public static void main (String [] args) {TreeSet ts=new TreeSet (), Ts.add (New Student ("Tan1"), Ts.add (New Student ("Tan3")), Ts.add (New Student (" Ts.add ("tan2"), "New Student (" Tan5 "); Iterator It=ts.iterator (); while (It.hasnext ()) {System.out.println ( It.next ());}}} Class Student implements Comparable{private string Name;private Integer age;public Student (string name, int age) {This.nam E = 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.) {this.age = age;} @Overridepublic String toString () {return ' name: ' +this.name+ ' + ' Age: ' +this.age;} @Overridepublic int compareTo (Object obj) {if (!) ( obj instanceof Student)) throw new RuntimeException ("Non-student object"); Student s= (Student) obj;if (this.age>s.age) return 1;//when sorting. When the main conditions are the same. Be sure to infer the secondary condition. if (this.age==s.age) {return this.name.compareTo (s.name);}return-1;}} 

define the comparison device yourself

Package Tan;import Java.util.comparator;import Java.util.iterator;import Java.util.treeset;public class TreeSetDemo { public static void Main (string[] args) {//in which it is possible to pass in its own definition TreeSet ts=new TreeSet (New Studentagecomparator ()); Ts.add (new Student ("Tan01"), Ts.add (New Student ("Tan03"), Ts.add (New Student ("Tan03"), Ts.add (New Student ("tan0012"); ), Ts.add (New Student ("tan007")), Iterator It=ts.iterator (); while (It.hasnext ()) {System.out.println (It.next ( ));}}} Class Student implements Comparable{private string Name;private Integer age;public Student (string name, int age) {This.nam E = 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.) {this.age = age;} @Overridepublic String toString () {return ' name: ' +this.name+ ' + ' Age: ' +this.age;} @Overridepublic int compareTo (Object obj) {if (!) ( obj instanceof Student)) throw new RuntimeException ("Non-student object"); Student s= (Student) obj;iF (this.age>s.age) return 1;//when sorting. When the main condition is the same, the secondary condition must be inferred. if (this.age==s.age) {return this.name.compareTo (s.name);} return-1;}} Define the name of the device class Studentnamecomparator implements comparator{@Overridepublic int Compare (object O1, Object O2) {Student s1= (Student) O1; Student s2= (Student) O2;int num=s1.getname (). CompareTo (S2.getname ()); if (num==0) {// Since Ingteger has implemented the comparable interface return new Integer (S1.getage ()). CompareTo (New Integer (S2.getage ()));//can also write/*if ( S1.getage () >s2.getage ()) Return 1;if (S1.getage () ==s2.getage ()) return 0;return-1;*/}return num;} Define your own age-comparison class Studentagecomparator implements comparator<student>{@Overridepublic int compare (Student O1, Student O2) {int i=o1.getage ()-o2.getage (); return i;}}

Exercise: Sort by string length.




The string itself is comparable, but its comparative method is not required, and only then can use the comparison device.

Package Tan;import java.util.*;p ublic class Treesettest {public static void main (string[] args) {TreeSet ts = new TreeSet ( New Strlengthcomparator ()), Ts.add ("ABCD"), Ts.add ("CC"), Ts.add ("CBA"), Ts.add ("AAA"), Ts.add ("Z"); Ts.add ("hahaha") ; Iterator it = Ts.iterator (); while (It.hasnext ()) {System.out.println (It.next ());}}} Class Strlengthcomparator implements Comparator {@Overridepublic int Compare (object O1, Object O2) {string S1 = (string) o 1; String s2 = (string) o2;int num = new Integer (S1.length ()). CompareTo (New Integer (S2.length ()));//When the first condition is met, Infer that the second condition is sorted according to natural order if (num==0) {return s1.compareto (s2);} return num;}}


TreeSet sorting, storing your own definition object, and defining the comparison as a sample

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.