package cn.book.objectarr;/*** @author alina* @date 2021年08月22日 6:57 下午*/
public class Student implements Comparable<Student> {private String name;private int age;public Student(){}/***** @author Alina* @date 2021/9/21 9:41 下午* @param o* @return int* 使用构造方法的自然排序方式*/public int compareTo(Student o ){//String类自带comparaTo();int num = this.name.compareTo(o.name);return num==0?this.age - o.age:num;
// if(num==0){
// return this.age - o.age;
// }else{
// return num;
// }}public Student(String name,int age){this.age = age;this.name = name;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return this.age;}public void setAge(int age) {this.age = age;}public String toString(){return "Student"+" "+name+" "+age;}public boolean equals(Object o){if (o == null) {return false;}else if(this == o){return true;}else if (o instanceof Student){Student s = (Student) o;return this.name.equals(s.name) && this.age == s.age;}return false;}public int hasCode(){return name.hashCode() +age*39;}}
public class TreeSetDemo {public static void main(String[] args) {//以姓名为顺序排序;method_1();//以年龄为顺序排序method_2();}public static void method_1(){TreeSet<Student> tr = new TreeSet<>();tr.add(new Student("zhangsan",12));tr.add(new Student("lisi",13));tr.add(new Student("wanger",56));tr.add(new Student("lisi",14));Iterator it = tr.iterator();while (it.hasNext()){System.out.println(it.next());}}
package cn.book.objectarr;import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;/*** @author Alina* @date 2021年09月21日 8:50 下午*/
class myCompatato implements Comparator<Student>{@Overridepublic int compare(Student o1, Student o2) {int age = o1.getAge() - o2.getAge();return age == 0? o1.getName().compareTo(o2.getName()):age;}
}
public class TreeSetDemo {public static void main(String[] args) {//以年龄为顺序排序method_2();}public static void method_2(){TreeSet<Student> tr = new TreeSet<>( new myCompatato());tr.add(new Student("zhangsan",12));tr.add(new Student("lisi",13));tr.add(new Student("wanger",56));tr.add(new Student("lisi",14));Iterator it = tr.iterator();while (it.hasNext()){System.out.println(it.next());}}}