集合框架_TreeSet儲存自定義物件並遍歷練習2)
阿新 • • 發佈:2018-12-25
package cn.itcast_06; import java.util.TreeSet; import cn.itcast_06.Student; /* * 需求:請按照姓名的長度排序 */ public class TreeSetDemo { public static void main(String[] args) { // 建立集合物件 TreeSet<Student> ts = new TreeSet<Student>(); // 建立學生物件 Student s1 = new Student("linqingxia", 27); Student s2 = new Student("zhangguorong", 29); Student s3 = new Student("wanglihong", 23); Student s4 = new Student("linqingxia", 27); Student s5 = new Student("liushishi", 22); Student s6 = new Student("wuqilong", 40); Student s7 = new Student("fengqingyang", 22); Student s8 = new Student("linqingxia", 29); // 新增元素 ts.add(s1); ts.add(s2); ts.add(s3); ts.add(s4); ts.add(s5); ts.add(s6); ts.add(s7); ts.add(s8); // 遍歷 for (Student s : ts) { System.out.println(s.getName() + "---" + s.getAge()); } } }
package cn.itcast_06; /* * 如果一個類的元素要想能夠進行自然排序,就必須實現自然排序介面 */ public class Student implements Comparable<Student> { private String name; private int age; public Student() { super(); // TODO Auto-generated constructor stub } public Student(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int compareTo(Student s) { // 主要條件 int num = this.name.length() - s.name.length(); // 姓名的長度相同,不代表姓名的內容相同 int num2 = num == 0 ? this.name.compareTo(s.name) : num; // 姓名的長度和內容相同,不代表年齡相同,所以還得繼續判斷年齡 int num3 = num2 == 0 ? (this.age - s.age) : num2; return num3; } }