知识是用来运用的,一辈子用不上的等于没学,学了忘了的等于没学,学了不会用的等于没学
//TreeSetDemo2.java package saturday2; import java.util.HashSet; import java.util.Iterator; import java.util.TreeSet; public class TreeSetDemo2 { public static void main(String[] args) { TreeSet<Student> t=new TreeSet<Student>(); Student s1 = new Student("liudehua",52); Student s2 = new Student("chenglong",60); Student s3 = new Student("zhouxingchi",44); Student s4 = new Student("sunyang",34); Student s5 = new Student("lingqingxia",36); Student s6 = new Student("lingqingxia",26); Student s7 = new Student("lingqing",26); t.add(s1); t.add(s2); t.add(s3); t.add(s4); t.add(s5); t.add(s6); t.add(s7); for(Student st:t){ System.out.println(st); } System.out.println("=================="); System.out.println("华丽的分割线"); System.out.println("=================="); Iterator<Student> iterator1 = t.iterator(); while(iterator1.hasNext()){ System.out.println(iterator1.next()); } } } package saturday2; public class Student implements java.lang.Comparable {//实现Comparable接口,对对象数组排序 private String name; private int age; public Student(){ super(); } 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 boolean equals(Object obj){ if(this==obj){ return true; } if(!(obj instanceof Student)){ return false; } Student s = (Student) obj; return(this.age==s.age); } @Override public int compareTo(Object o){ // 实现 Comparable 接口的抽象方法,定义排序规则 Student p = (Student)o; return this.age - p.age; // 升序排列,反之降序 } @Override public String toString(){ return("Student [name="+name+",age="+age+"]"); } }
|