Java basics-TreeSet, javatreeset
TreeSet is the implementation class of the SortedSet interface. Sorted is classified in English.
TreeSet ensures that the elements of the set are sorted. Compared with the HashSet set, TreeSet provides the following additional methods:
Method Name |
Explanation |
Comparator comparator (); |
If the TreeSet adopts the custom sorting, Comparator is returned for the custom sorting. If the TreeSet adopts the natural sorting, null is returned; |
Object first (); |
Returns the first element in the set; |
Object last (); |
Returns the last element of the set; |
Object lower (Object o ); |
Returns the elements in the set that are located before the specified Element (that is, the maximum element smaller than the specified element, the reference element does not need to be an element in the TreeSet set ); |
Object higher (Object o ); |
Returns the elements located after the specified Element in the collection (that is, the smallest element greater than the specified element. The reference element does not need to be an element in the TreeSet set ); |
SortedSet subSet (Object fromElement, Object toElement ); |
Returns the child Set of this Set, and returns the toElement (not included) from fromElement, Object (included ); |
SortedSet headSet (Object toElement ); |
Returns a subset of the Set, which consists of elements smaller than the toElement; |
SortedSet tailSet (Object fromElement ); |
Returns a subset of the Set, which consists of elements greater than or equal to fromElement; |
1 import java. util. set; 2 import java. util. treeSet; 3 4 public class TreeS {5 public static void main (String [] args) {6 Set <String> set = new TreeSet <String> (); // defines generic 7 set. add ("Java"); 8 set. add ("Js"); 9 set. add ("PHP"); 10 set. add ("C #"); 11 set. add ("C ++"); 12 set. add (". net "); 13 // print the collection 14 System. out. println (set); 15 16 // The capacity of the output set is 17 System. out. println (set. size (); 18 19 // if this set does not contain any elements, true20 System is returned. out. println (set. isEmpty (); 21 22} 23}
output:[.Net, C#, C++, Java, Js, PHP]6false
Unlike the HashSet set, the hash algorithm is used to determine the storage location of elements. TreeSet uses the data structure of the red/black tree to store the set elements.
TreeSet supports two sorting methods: Natural sorting and custom sorting.
I. Natural sorting:
TreeSet calls the compareTo (Object o) method of the Set element to compare the size relationship between elements, and then sorts the set elements in ascending order. This is a natural sorting method.
Java provides a Comparable interface that defines a compareTo (Object o) method. This method returns an integer and the class that implements this interface must implement this method, the object of the class implementing this interface can be compared.
Example 1 & Example 2:
1 import java. util. treeSet; 2 3 public class T {4 public static void main (String [] args) {5 6 // Example 1: number sorting 7/* 8 * TreeSet a = new TreeSet (); 9 *. add (10); 10 *. add (55); 11 *. add (4); 12 *. add (6); 13 *. add (-1); 14 *. add (-77); 15 *. add (0); 16*17 * System. out. println (a); // print: [-77,-1, 0, 4, 6, 10, 55] 18 */19 20 // Example 2: 21 TreeSet ts = new TreeSet (); 22 ts. add ("B"); 23 ts. add ("ee"); 24 ts. add ("d"); 25 ts. add ("abc"); 26 ts. add ("ca"); 27 28/* abc29 b30 c31 ca32 d33 ee */34 35 System. out. println (ts); // [abc, B, ca, d, ee] 36} 37}
Example 3: (the following example shows no specific comparison rules .)
1 import java. util. set; 2 import java. util. treeSet; 3 4 class TreeS implements Comparable <Object> {5 6 int score; 7 8 public TreeS (int score) {9 this. score = score; 10} 11 12 public int compareTo (Object o) {13 return 1; 14} 15 16 public boolean equals (Object obj) {17 return true; 18} 19 20 public static void main (String [] args) {21 Set <Object> set = new TreeSet <Object> (); 22 23 // we plan to add two objects in 24 set. add (new TreeS (77); 25 set. add (new TreeS (7); 26 27 System. out. println (set); 28 29} 30}
output:[TreeS@67064, TreeS@bcda2d]
Example 4: (this example is used to introduce a custom calculation method)
The criteria for determining whether two objects are equal are as follows:
1 import java. util. set; 2 import java. util. treeSet; 3 4 class TreeS implements Comparable <Object> {5 6 int score; 7 8 public TreeS (int score) {9 this. score = score; 10} 11 12 public int compareTo (Object o) {13 TreeS d = (TreeS) o; // force type conversion 14 return this. score> d. score? 1: this. score <d. score? -1:0; 15} 16 17 public boolean equals (Object obj) {18 if (this = obj) {19 return true; 20} else if (obj! = Null & obj. getClass () = TreeS. class) {21 TreeS d = (TreeS) obj; 22 return d. score = this. score; 23} 24 return false; 25} 26 27 public static void main (String [] args) {28 Set <Object> set = new TreeSet <Object> (); 29 30 // you are planning to add two objects in 31 set. add (new TreeS (77); 32 set. add (new TreeS (77); // 33 set not printed. add (new TreeS (20); 34 set. add (new TreeS (3); 35 set. add (new TreeS (44); 36 set. add (new TreeS (44); // 37 set not printed. add (new TreeS (6); 38 set. add (new TreeS (-11); 39 set. add (new TreeS (9); 40 set. add (new TreeS (0); 41 42 System. out. println (set); 43 44} 45}
output:[TreeS@97d01f, TreeS@e0a386, TreeS@feb48, TreeS@11ff436, TreeS@da3a1e, TreeS@11dba45, TreeS@b03be0, TreeS@2af081]
Note:
Similar to HashSet, if a TreeSet contains a mutable object, when the sample variable of the mutable object is modified, the TreeSet is complex and error-prone when processing these objects. To make the program more robust, we recommend that you do not modify the key instance variables that are placed in elements in the HashSet and TreeSet sets.
Ii. Custom sorting
The natural sorting of TessSet is based on the size of the Set elements, which are arranged in ascending order by TreeSet. You can use the Comparator interface to help you sort data in descending order.
Example 1:
// Use TreeSet to sort students' test scores. // how can this problem be solved? // 1 Let the object implement the Comparable interface // 2 and then rewrite the compareTo method // interface Comparable <T> Comparable interface // int compareTo (T o) the Comparable interface returns a negative integer, zero, or positive integer based on whether the object is smaller than, equal to, or greater than the specified object. Public class Student implements Comparable <Object> {int age; int score; String name; @ Override // when rewriting by yourself, write it first to help you report public String toString () {return this. name + ":" + this. age + ":" + this. score;} public Student (int age, int score, String name) {this. name = name; this. age = age; this. score = score ;}@ Override // the return value is positive, negative, or zero to determine the size of public int compareTo (Object obj) {if (! (Obj instanceof Student) {throw new RuntimeException ("this class object is not input. Please input it again") ;}student stu = (Student) obj; if (this. score> stu. score) {return 1; // set it to a positive number.} else if (this. score <stu. score) {return-1;} else {// if the setting is equal, the preceding example shows that data will be lost if the values are equal. int result = this must be taken into account here. name. compareTo (stu. name); if (result = 0) return 1; return result ;}}}
Test class:
Import java. util. iterator; import java. util. set; import java. util. treeSet; public class Test {public static void main (String [] args) {Set <Student> treeSet = new TreeSet <Student> (); treeSet. add (new Student (11, 80, "Li Ping"); treeSet. add (new Student (23, 40, "Wang Fang"); treeSet. add (new Student (10, 60, "Zhao Lei"); treeSet. add (new Student (12, 40, "Wang xiao'er"); treeSet. add (new Student (10, 60, "Ma Miao"); treeSet. add (new Student (18, 60, "Ma Miao"); treeSet. add (new Student (25, 70, "Jiang Hao"); Iterator <Student> it = treeSet. iterator (); while (it. hasNext () {Student stu = (Student) it. next (); System. out. println (stu );}}}
Example 2:
// Put the string in the treeset In the example and sort the class MyComparator implements Comparator {@ Override public int compare (Object o1, Object o2) {Student stu1 = (Student) o1; student stu2 = (Student) o2; if (stu1.score> stu2.score) {return 10; // if it is a positive number} else if (stu1.score <stu2.score) {return-10 ;} else {// return 0; return stu1.name. compareTo (stu2.name) ;}} Set set = new TreeSet (new StrLenComparator (); Set. add ("cc"); set. add ("B"); set. add ("dddddddd"); set. add ("kkkkkkkkkk"); set. add ("v"); set. add ("ee"); set. add ("sssss"); Iterator it2 = set. iterator (); while (it2.hasNext () {System. out. println (it2.next ());}
Example 3:
Appendix: Use the Anonymous class Set = new TreeSet (new Comparator () {// here the Anonymous class @ Override public int compare (Object o1, Object o2) is used) {String str1 = (String) o1; String str2 = (String) o2; if (str1.length ()> str2.length () {return 1;} else if (str1.length () <str2.length () {return-1;} else {// return 0; return 1; // if they are equal, the objective of returning 1 is to fear data loss }}}
Summary:
TreeSet is implemented by TreeMap. Therefore, it judges whether the elements are repeated based on the implemented Compareble interface or Comparator interface, and its sorting is the same as that of TreeMap.