标签:
1. TreeSet存储自定义对象并遍历练习2:
(1)Student.java
1 package cn.itcast_06; 2 3 /* 4 * 如果一个类的元素要想能够进行自然排序,就必须实现自然排序接口 5 */ 6 public class Student implements Comparable<Student> { 7 private String name; 8 private int age; 9 10 public Student() { 11 super(); 12 } 13 14 public Student(String name, int age) { 15 super(); 16 this.name = name; 17 this.age = age; 18 } 19 20 public String getName() { 21 return name; 22 } 23 24 public void setName(String name) { 25 this.name = name; 26 } 27 28 public int getAge() { 29 return age; 30 } 31 32 public void setAge(int age) { 33 this.age = age; 34 } 35 36 @Override 37 public int compareTo(Student s) { 38 // 主要条件 姓名的长度 39 int num = this.name.length() - s.name.length(); 40 // 姓名的长度相同,不代表姓名的内容相同 41 int num2 = num == 0 ? this.name.compareTo(s.name) : num; 42 // 姓名的长度和内容相同,不代表年龄相同,所以还得继续判断年龄 43 int num3 = num2 == 0 ? this.age - s.age : num2; 44 return num3; 45 } 46 }
(2)TreeSetDemo.java:
1 package cn.itcast_06; 2 3 import java.util.TreeSet; 4 5 /* 6 * 需求:请按照姓名的长度排序 7 */ 8 public class TreeSetDemo { 9 public static void main(String[] args) { 10 // 创建集合对象 11 TreeSet<Student> ts = new TreeSet<Student>(); 12 13 // 创建元素 14 Student s1 = new Student("linqingxia", 27); 15 Student s2 = new Student("zhangguorong", 29); 16 Student s3 = new Student("wanglihong", 23); 17 Student s4 = new Student("linqingxia", 27); 18 Student s5 = new Student("liushishi", 22); 19 Student s6 = new Student("wuqilong", 40); 20 Student s7 = new Student("fengqingy", 22); 21 Student s8 = new Student("linqingxia", 29); 22 23 // 添加元素 24 ts.add(s1); 25 ts.add(s2); 26 ts.add(s3); 27 ts.add(s4); 28 ts.add(s5); 29 ts.add(s6); 30 ts.add(s7); 31 ts.add(s8); 32 33 // 遍历 34 for (Student s : ts) { 35 System.out.println(s.getName() + "---" + s.getAge()); 36 } 37 } 38 }
运行结果,如下:
Java基础知识强化之集合框架笔记46:Set集合之TreeSet存储自定义对象并遍历练习2(自然排序)
标签:
原文地址:http://www.cnblogs.com/hebao0514/p/4857795.html