1. TreeSet Store your custom objects and traverse Exercise 2:
(1)Student. java
1 Packagecn.itcast_06;2 3 /*4 * If an element of a class wants to be able to sort naturally, it must implement the natural sort interface5 */6 Public classStudentImplementsComparable<student> {7 PrivateString name;8 Private intAge ;9 Ten PublicStudent () { One Super(); A } - - PublicStudent (String name,intAge ) { the Super(); - This. Name =name; - This. Age =Age ; - } + - PublicString GetName () { + returnname; A } at - Public voidsetName (String name) { - This. Name =name; - } - - Public intGetage () { in returnAge ; - } to + Public voidSetage (intAge ) { - This. Age =Age ; the } * $ @OverridePanax Notoginseng Public intCompareTo (Student s) { - //the length of the primary condition name the intnum = This. Name.length ()-s.name.length (); + //name is the same length, does not mean that the name is the same content A intnum2 = num = = 0? This. Name.compareto (s.name): num; the //the name is the same length and content, does not mean the same age, so you have to continue to judge the age + intnum3 = Num2 = = 0? This. Age-s.age:num2; - returnnum3; $ } $}
(2)Treesetdemo. Java:
1 Packagecn.itcast_06;2 3 ImportJava.util.TreeSet;4 5 /*6 * Requirements: Please follow the name of the length of the order7 */8 Public classTreesetdemo {9 Public Static voidMain (string[] args) {Ten //To create a collection object Onetreeset<student> ts =NewTreeset<student>(); A - //Creating Elements -Student S1 =NewStudent ("Linqingxia", 27); theStudent s2 =NewStudent ("Zhangguorong", 29); -Student s3 =NewStudent ("Wanglihong", 23); -Student S4 =NewStudent ("Linqingxia", 27); -Student S5 =NewStudent ("Liushishi", 22); +Student s6 =NewStudent ("Wuqilong", 40); -Student s7 =NewStudent ("Fengqingy", 22); +Student S8 =NewStudent ("Linqingxia", 29); A at //adding elements - Ts.add (S1); - ts.add (S2); - Ts.add (S3); - Ts.add (S4); - Ts.add (S5); in Ts.add (S6); - Ts.add (S7); to Ts.add (S8); + - //Traverse the for(Student s:ts) { *System.out.println (S.getname () + "---" +s.getage ()); $ }Panax Notoginseng } -}
Run the results as follows:
Java Basic Knowledge Hardening Collection Framework note 46:set Collection TreeSet store custom objects and traverse Exercise 2 (natural sort)