Java Bi Xiangdong Lecture note 25 (Collection frame-set collection TreeSet)

Source: Internet
Author: User
Tags comparable

TreeSet: You can sort the elements in the set collection.


Example: Storing a custom object

Import java.util.*;/* Requirements: Store custom objects in the TreeSet collection-students want to sort by student's age */class student{private String name;private int ages; Student (String Name,int age) {this.name = Name;this.age = age;} Public String GetName () {return name;} public int getage () {return age;}} Class Treesetdemo{public static void Main (string[] args) {TreeSet ts = new TreeSet (); Ts.add (New Student ("lisi02", 22)); Ts.add (New Student ("lisi007")), Ts.add (New Student ("lisi09"), Ts.add (New Student ("lisi01", +)); Iterator it = Ts.iterator (), while (It.hasnext ()) {Student Stu = (Student) it.next (), SOP (Stu.getname () + "::" +stu.getage ());}} public static void Sop (Object obj) {System.out.println (obj);}}

However, the output is:


This is because TreeSet automatically sorts, but the custom objects we store are not comparable, so error.

Workaround: Let the student class implement the comparable interface, forcing students to have a comparative

Import java.util.*;/* Requirements: Store custom objects in the TreeSet collection-students want to sort by student's age */class Student implements comparable{private String name; private int age; Student (String Name,int age) {this.name = Name;this.age = age;} public int compareTo (Object obj) {if (!) ( obj instanceof Student)) throw new RuntimeException ("Not student object"); Student s = (Student) Obj;return this.age-s.age;} Public String GetName () {return name;} public int getage () {return age;}} Class Treesetdemo{public static void Main (string[] args) {TreeSet ts = new TreeSet (); Ts.add (New Student ("lisi02", 22)); Ts.add (New Student ("lisi007")), Ts.add (New Student ("lisi09"), Ts.add (New Student ("lisi01", +)); Iterator it = Ts.iterator (), while (It.hasnext ()) {Student Stu = (Student) it.next (), SOP (Stu.getname () + "::" +stu.getage ());}} public static void Sop (Object obj) {System.out.println (obj);}}


What happens if you have the same age and different names?

Import java.util.*;/* Requirements: Store custom objects in the TreeSet collection-students want to sort by student's age */class Student implements comparable{private String name; private int age; Student (String Name,int age) {this.name = Name;this.age = age;} public int compareTo (Object obj) {if (!) ( obj instanceof Student)) throw new RuntimeException ("Not student object"); Student s = (Student) Obj;return this.age-s.age;} Public String GetName () {return name;} public int getage () {return age;}} Class Treesetdemo{public static void Main (string[] args) {TreeSet ts = new TreeSet (); Ts.add (New Student ("lisi02", 22)); Ts.add (New Student ("lisi007")), Ts.add (New Student ("lisi09"), Ts.add (New Student ("lisi01", +)), Ts.add (new Student ("lisi08"), Iterator it = Ts.iterator (); while (It.hasnext ()) {Student Stu = (Student) it.next (); SOP ( Stu.getname () + "::" +stu.getage ());}} public static void Sop (Object obj) {System.out.println (obj);}}

Discover that new elements are not being stored because, according to the comparison rules, the same age represents the same element, and the element is not stored according to the non-repeatability. How to solve? As follows:

Import java.util.*;/* Requirements: Store custom objects in the TreeSet collection-students want to sort by student's age */class Student implements comparable{private String name; private int age; Student (String Name,int age) {this.name = Name;this.age = age;} public int compareTo (Object obj) {if (!) ( obj instanceof Student)) throw new RuntimeException ("Not student object"); Student s = (Student) obj;if (this.age>s.age) return 1;if (this.age==s.age) {return this.name.compareTo (s.name);} return-1;} Public String GetName () {return name;} public int getage () {return age;}} Class Treesetdemo{public static void Main (string[] args) {TreeSet ts = new TreeSet (); Ts.add (New Student ("lisi02", 22)); Ts.add (New Student ("lisi007")), Ts.add (New Student ("lisi09"), Ts.add (New Student ("lisi01", +)), Ts.add (new Student ("lisi08"), Iterator it = Ts.iterator (); while (It.hasnext ()) {Student Stu = (Student) it.next (); SOP ( Stu.getname () + "::" +stu.getage ());}} public static void Sop (Object obj) {System.out.println (obj);}}

Summary: When sorting, when the main conditions are the same, be sure to judge the secondary conditions
---------------------------------------------------------------------------------

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

TreeSet the first way of ordering: to make the elements themselves comparable, elements need to implement comparable interfaces, overriding CompareTo methods, which is also called the natural order of the elements, or the default order

The second sort of TreeSet collection: When the element itself is not comparable, or the comparison is not required, then it is necessary to make the collection itself comparative. When the collection is initialized, there is a comparison method

Import java.util.*;/* When the element itself is not comparable, or if the comparison is not required, then the container itself needs to be comparative. A comparer is defined that passes the comparer object as a parameter to the constructor of the TreeSet collection when both sorts are present, the comparator is the primary definition of a class, and the comparator interface is implemented. Overwrite Compare method (note: Comparable inside is CompareTo method) */class Student implements comparable{private String name;private int age; Student (String Name,int age) {this.name = Name;this.age = age;} public int compareTo (Object obj) {if (!) ( obj instanceof Student)) throw new RuntimeException ("Not student object"); Student s = (Student) obj;if (this.age>s.age) return 1;if (this.age==s.age) {return this.name.compareTo (s.name);} return-1;} Public String GetName () {return name;} public int getage () {return age;}} Class Treesetdemo2{public static void Main (string[] args) {TreeSet ts = new TreeSet (); Ts.add (New Student ("lisi02"); TS . Add (New Student ("lisi007")), Ts.add (New Student ("lisi007"), Ts.add (New Student ("lisi09", +)); Ts.add (new Student ("lisi01"); Ts.add (New Student ("lisi08", +)); Iterator it = Ts.iterator (); while (It.hasnext ()) {Student Stu = (Student) It.next (); SOP (Stu.getname () + "::" +stu.getage());}} public static void Sop (Object obj) {System.out.println (obj);}} Class Mycompare implements Comparator{public int compare (Object o1,object O2) {Student S1 = (Student) O1; Student s2 = (Student) o2;int num = S1.getname (). CompareTo (S2.getname ()); if (num==0) {if (S1.getage () >s2.getage ()) Return 1;if (S1.getage () ==s2.getage ()) return 0;return-1;//simpler notation: return new Integer (S1.getage ()). CompareTo (New Integer (S2.getage ()));} return num;}}


-----------------------------------------------------------------------

TreeSet Exercise: Sort by string length

The code at the beginning is as follows:

/* The string itself is comparable, but it is not required to be compared, then you can only use the comparator */import java.util.*;class treesettest{public static void Main (string[] args) { TreeSet ts =new TreeSet () ts.add ("ABCD"), Ts.add ("CC"), Ts.add ("CBA"), Ts.add ("Z"); Ts.add ("hahaha"); Iterator it = Ts.iterator (); while (It.hasnext ()) {SOP (It.next ());}} public static void Sop (Object obj) {System.out.println (obj);}}
Result is

Obviously it's not what we want.

/* The string itself is comparable, but it is not required to be compared, then you can only use the comparator */import java.util.*;class treesettest{public static void Main (string[] args) { TreeSet TS =new TreeSet (new Stringlengthcomparator ()), Ts.add ("ABCD"), Ts.add ("CC"), Ts.add ("CBA"), Ts.add ("Z"); ts.add ("hahaha"); Iterator it = Ts.iterator (); while (It.hasnext ()) {SOP (It.next ());}} public static void Sop (Object obj) {System.out.println (obj);}} Class Stringlengthcomparator implements Comparator{public int compare (Object o1,object O2) {string S1 = (string) O1; String s2 = (string) o2;return s1.length ()-s2.length ();}}

Can be optimized: when the same length, different content of the string, because the same length is considered the same element, not be stored in, so in the implementation of the comparator interface class should be judged when the length of the same time, the string content comparison. That

Class Stringlengthcomparator implements Comparator{public int compare (Object o1,object O2) {string S1 = (string) O1; String s2 = (string) o2;//return s1.length ()-s2.length (); int num = new Integer (S1.length ()). CompareTo (New Integer ( S2.length ())); if (num==0) return S1.compareto (S2); return num;}}



Java Bi Xiangdong Lecture note 25 (Collection frame-set collection 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.