Import java.text.parseexception;import java.text.simpledateformat;import java.util.date;import java.util.Iterator;import java.util.SortedSet;import java.util.TreeSet;public class sortedsettest {/** * @param args */public static void main (String[] args) {// todo auto-generated method stub // 1. Create the collection Sortedset ss = new treeset (); //2. Add elements to the collection Ss.add (1);// Automatic boxing Ss.add (3); Ss.add (2); Ss.add (-1);//3. Traverse output Iterator it = ss.iterator (); while (It.hasnext ()) { System.out.println (It.next ());} System.out.println ("========================================="); Ss.clear ();//Add String Ss.add ("Nihao") to the collection; Ss.add (" Wobuhao "); Ss.add (" Wohenhao "); Ss.add (" Weishenmehuizheyang? "); It = ss.iterator (); while (It.hasnext ()) {System.out.println (It.next ());} System.out.println ("========================================="); Ss.clear ();//Add the date string st1 = "2008-08-08" to the collection; string st2 = "2009-08-08"; string st3 = "2008-09-08"; string st4 = "2008-08-09"; string st5 = "2012-08-08"; Simpledateformat sdf = new simpledateformat ("Yyyy-mm-dd"); try {date date1 = Sdf.parse (ST1);D ate date2 =sdf.parse (ST2);D ate date3 =sdf.parse (ST3);D ate date4 =sdf.parse (ST4);D ate date5 =sdf.parse (ST5); Ss.add (date1); Ss.add (date2); Ss.add (Date3); Ss.add (DATE4); Ss.add (DATE5);} catch (parseexception e) {e.printstacktrace ();} It = ss.iterator (); while (It.hasnext ()) {System.out.println (It.next ());} System.out.println ("=============================="); Ss.clear ();//Add a custom element to the collection useruser u1 = new user ("Zhangdan"); User u2 = new user ("Lisi"); User u3 = new user (5, "Naliu"); Ss.add (U1); Ss.add (U2); Ss.add (U3); It = ss.Iterator (); while (It.hasnext ()) {System.out.println (It.next ());} System.out.println ("==============================");}} /** * Why the elements exist are automatically sorted, because they implement the Comprable interface, and the Comprareto () method is called when an element is present. */ User
User1 implements the Comprable interface, or it defines a comparator
public class User implements comparable{
private int age;
private String name;
Public User (int age,string name) {
This.age = age;
THIS.name = name;
}
Public User () {
}
@Override
public int compareTo (Object o) {
int Age1 =this.age;
int age2 = ((User) O). Age;
return age1-age2;
}
Public String toString () {
Return "Name=" + name + "age=" +age;
}
}
This article is from the "Gaogaozi" blog, make sure to keep this source http://hangtiangazi.blog.51cto.com/8584103/1669870
The Sortset collection in Java