The SortedSet in set (SortedSet is the implementation interface for TreeSet), and the inheritance between them is as follows:
Java.util.Set;
Java.util.SortedSet;
Java.util.TreeSet;
The elements in the SortedSet are unordered and cannot be duplicated, but the elements that are stored can be sorted automatically in order of the element size. Combine the following code to see:
Import java.util.*;
Import java.text.*;
PublicClasssortedsettest01{
PublicStaticvoidMainString[] args) throws exception{
SortedSet ss=NewTreeSet ();
Number class
Ss.Add12);
Ss.Add23);
Ss.Add45);
Ss.Add39);
Ss.Add45);
Iterator It=ss.iterator ();
while (It.hasnext ()) {
System.Out.println (It.next ());
}
String class
SortedSet str=NewTreeSet ();
Str.Add"JACK");
Str.Add"TOM");
Str.Add"KING");
Str.Add"SUN");
It=str.iterator ();
while (It.hasnext ()) {
System.Out.println (It.next ());
}
Date class
String st1="2003-08-12";
String st2="2004-09-17";
String st3="2003-04-12";
String st4="2013-09-04";
SimpleDateFormat sdf= new simpledateformat ( "Yyyy-mm-dd");
date T1=sdf.parse (ST1);
date t2=sdf.parse (ST2);
date t3=sdf.parse (ST3);
date t4=sdf.parse (ST4);
sortedset times= new treeset ();
times. Add (T1);
times. Add (T2);
times. Add (T3);
times. Add (T4);
it=times.iterator ();
while (It.hasnext ()) {
object element=it.next ();
if (element instanceof Date) {
date d= (date) element;
system. out.println (Sdf.format (d));
 }
 }
}
}
After compiling the run-time output:
12
23
39
45
JACK
KING
SUN
TOM
2003-04-12
2003-08-12
2004-09-17
2013-09-04
The code above shows that elements that exist in SortedSet can be sorted by element size, which can be a number class, a string class, or a date class. Now that you know this feature of SortedSet, why is the SortedSet collection storage element automatically sorted?
In the above code, we implemented the automatic ordering of numbers, strings, and date classes in SortedSet, so if we were to customize several user type objects and then add them to the SortedSet collection, could we implement an automatic sort like above? Try it.
Import java.util.*;
PublicClasssortedsettest02{
PublicStaticvoidMainString[] (args) {
SortedSet users=NewTreeSet ();
User u1=NewUser (12);
User u2=NewUser (16);
User u3=NewUser (23);
User u4=NewUser (32);
User u5=NewUser (43);
Users.Add (U1);
Users. Add (U2);
users. Add (U3);
users. Add (U4);
users. Add (U5);
iterator it=users.iterator ();
while (It.hasnext ()) {
system. Out.println (It.next ());
 }
}
}
class  user{
int age;
user ( int age) {
this.age=age;
}
public string   toString () {
return  " user[age= "+age+ "] ";
}
}
Compile pass, error after running, output:
Exception in thread "main" Java.lang.ClassCastException:User cannot is cast to java.lang.Comparable
At Java.util.TreeMap.compare (Unknown Source)
At Java.util.TreeMap.put (Unknown Source)
At Java.util.TreeSet.add (Unknown Source)
At Sortedsettest02.main (sortedsettest02.java:14)
User cannot is cast to java.lang.Comparable, which means the user cannot be converted to a comparable type. So the user must implement the comparable interface (that is, the number in the first program example, the string, the date underlying has implemented the comparable interface), that is, the class User implements comparable{}. We know that a class implements an interface to implement all the methods of this interface, and that the elements in the SortedSet collection can be automatically sorted because the elements added using the Add () method implement the CompareTo () method in the comparable interface.
In the code above, if we are given a requirement to sort by the age of user, then we need to write a comparison rule,
public int compareTo(Object o){
//编写一个比较规则
int age1=this.age;
int age2=((User)o).age;
return age1-age2;
}
The usage of CompareTo is U1.compareto (U2), this is U1, the parameter O in parentheses is U2, because the argument type in parentheses is the object type, and the object type has no age attribute, so the O coercion type must be converted to the user type, i.e. ( User) O. The overall code after the modification is as follows:
Import java.util.*;
PublicClasssortedsettest02{
Public StaticvoidMainString[] (args) {
SortedSet users=NewTreeSet ();
User u1=NewUser (12);
User u2=NewUser (16);
User u3=NewUser (23);
User u4=NewUser (32);
User u5=NewUser (43);
Users.Add (U1);
Users.Add (U2);
Users.Add (U3);
Users.Add (U4);
Users.Add (U5);
Iterator It=users.iterator ();
while (It.hasnext ()) {
System.Out.println (It.next ());
}
}
}
ClassUserImplementscomparable{
IntAge
User (IntAge) {
This.age=age;
}
PublicString toString () {
return  "User[age=" +age+ "]";
}
//implement java.lang.Comparable; The CompareTo method in the interface
//The method programmer is responsible for the implementation, and the program that Sun provided has called the method
//Requirements: Sort by user's age
public&NBSP; int< Span class= "Apple-converted-space" >&NBSP; compareTo ( Object o) { //u1.compareto (U2)
//write a comparison rule
int age1= This.age; &NBSP;
int return&NBSP;AGE1-AGE2;
}
}
After compiling the run-time output:
User[age=12]
User[age=16]
User[age=23]
User[age=32]
User[age=43]
In addition, there is another way to implement SortedSet collection ordering: use Java.util.Comparator; to write a comparer separately, to create a TreeSet collection with this comparator, SortedSet products=new TreeSet (New Productcomparator ()); The code is as follows:
Import java.util.*;
PublicClasssortedsettest03{
PublicStaticvoidMainString[] (args) {
Provides a comparer when creating a TreeSet collection
SortedSet products=NewTreeSet (NewProductcomparator ());
Product p1=NewProduct (3.4);
Product p2=NewProduct (4.0);
Product p3=NewProduct (3.6);
Product p4=NewProduct (7.6);
Product p5=NewProduct (3.7);
Products.Add (p1);
Products.Add (p2);
Products.Add (p3);
Products.Add (p4);
Products.Add (p5);
Iterator It=products.iterator ();
while (It.hasnext ()) {
System.Out.println (It.next ());
}
}
}
Classproduct{
DoublePrice
Product (DoublePrice) {
This.price=price;
}
PublicStringToString (){
ReturnPrice +"";
}
}
Write a comparator separately
ClassProductcomparatorImplementscomparator{
Requirements: sorted by commodity price
public&NBSP; int Compare ( Object o1,object O2) {
double price1= (Product) O1). Price;
double price2= ((Product) O2). Price;
&NBSP if (price1==price2) {
Return&NBSP; 0;
} else&NBSP; if (price1>price2) {
return&NBSP; -1;
}
return&NBSP; 1;
}
}
After compiling the run-time output:
7.6
4.0
3.7
3.6
3.4
搜索公众号“程序员考拉”,欢迎关注!
Why is Java sortedset possible to automate sorting?