Student类:name、age属性 1 package com.bjpowernode.test01_set2_Comparable; 2 /* 3 * T: type 4 */ 5 public class Student implements Comparable<Student> { 6 private String name; 7 private int age; 8 public String getName() { 9 return name; 10 } 11 public void setName(String name) { 12 this.name = name; 13 } 14 public int getAge() { 15 return age; 16 } 17 public void setAge(int age) { 18 this.age = age; 19 } 20 public Student(String name, int age) { 21 super(); 22 this.name = name; 23 this.age = age; 24 } 25 public Student() { 26 super(); 27 // TODO Auto-generated constructor stub 28 } 29 /*@Override 30 public int hashCode() { 31 final int prime = 31; 32 int result = 1; 33 result = prime * result + age; 34 result = prime * result + ((name == null) ? 0 : name.hashCode()); 35 return result; 36 } 37 @Override 38 public boolean equals(Object obj) { 39 if (this == obj) 40 return true; 41 if (obj == null) 42 return false; 43 if (getClass() != obj.getClass())//判断两个“对象”的类型是否相同。 44 return false; 45 Student other = (Student) obj; //向下转型 46 if (age != other.age) 47 return false; 48 if (name == null) { //避免出现NullPointerException异常 49 if (other.name != null) 50 return false; 51 } else if (!name.equals(other.name)) 52 return false; 53 return true; 54 }*/ 55 /* 56 * 当前对象与参数对象相同时返回 : 0 57 * 当前对象 大于参数对象 时: 1 正数 58 * 当前对象 小于参数对象 时: -1 负数 59 */ 60 @Override 61 public int compareTo(Student s) { 62 //按年龄排序,如果年龄相同,按姓名排序 63 if(this.age == s.age){ 64 //按姓名排序, 调用字符串的compareTo 65 return this.name.compareTo(s.name); 66 } 67 return this.age -s.age; 68 } 69 70 }
TreeSet存储,遍历,排序输出 1 package com.bjpowernode.test01_set2_Comparable; 2 3 import java.util.TreeSet; 4 /* 5 * TreeSet中存放元素,默认按自然排序的方式去除重复项,并进行排序的 6 * String和8种包装类中都指定自然排序方法:实现java.lang.Comparable接口,重写compareTo方法 7 * 自定义的类放入TreeSet时,也实现实现java.lang.Comparable接口,重写compareTo方法 8 */ 9 public class StudentTreeSetTest { 10 public static void main(String[] args) { 11 TreeSet<Student> tree = new TreeSet<>(); 12 Student s = new Student("Mike", 18); 13 Student s1 = new Student("Join", 28); 14 Student s3 = new Student("Join", 18); 15 Student s4 = new Student("Smith", 18); 16 tree.add(s); 17 tree.add(s1); 18 tree.add(s3); 19 tree.add(s4); 20 System.out.println(tree.size()); 21 System.out.println("姓名\t年龄"); 22 for (Student stu : tree) { 23 System.out.println(stu.getName()+"\t"+stu.getAge()); 24 } 25 } 26 }
时间: 2024-11-09 06:24:33