排序 一、自然排序Comparable 1.存储学生对象并遍历,使用TreeSet的无参构造方法。
要求:按年龄从小到大排序,年龄相同时按姓名的字母顺序排序。
代码实现:
Student类:
package ComparableStudy; public class Student implements Comparable{ private String name; private int age; public Student() { } public Student(String name, int age) { 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; } @Override public int compareTo(Student o) { int num1; num1 = this.getAge() - o.getAge(); //当年龄相同的时候比较姓名 num1=(num1==0?this.name.compareTo(o.getName()):num1); return num1; //num1=0 --->表示相同元素,不插入 //num1>0 --->表示不同元素,升序 //num1<0 --->表示不同元素,降序 } }
Demo类:
package ComparableStudy;
import java.util.TreeSet;
public class Demo {
public static void main(String[] args) {
//创建集合对象
TreeSet ts = new TreeSet<>();
//创建学生对象
Student s1 = new Student("qwe", 11);
Student s2 = new Student("asd", 12);
Student s3 = new Student("zxc", 11);
Student s4 = new Student("wh", 10);
Student s5 = new Student("asd", 12);
//把对象存储到集合中
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
ts.add(s5);
//遍历
for (Student s : ts) {
System.out.println(s.getName() + "," + s.getAge());
}
}
}
2.总结
- 用TreeSet集合存储自定义对象,无参构造方法使用的是自然排序方法对元素进行排序
- 自然排序就是让元素所属的类实现Comparable接口,重写compareTo(T o)方法
- 重写方法时要按照需求来写
要求:按年龄从小到大排序,年龄相同时按姓名的字母顺序排序。
代码实现:
Student类:
package ComparableStudy;
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
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;
}
}
Demo:
package ComparableStudy;
import java.util.Comparator;
import java.util.TreeSet;
public class Demo {
public static void main(String[] args) {
//创建集合对象
TreeSet ts = new TreeSet<>(new Comparator() {
@Override
public int compare(Student s1, Student s2) {
int num;
num = s1.getAge() - s2.getAge();
//当年龄相同的时候比较姓名
num=(num==0?s1.getName().compareTo(s2.getName()):num);
return num;
}
});
//创建学生对象
Student s1 = new Student("qwe", 11);
Student s2 = new Student("asd", 12);
Student s3 = new Student("zxc", 11);
Student s4 = new Student("wh", 10);
Student s5 = new Student("asd", 12);
//把对象存储到集合中
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
ts.add(s5);
//遍历
for (Student s : ts) {
System.out.println(s.getName() + "," + s.getAge());
}
}
}
2.总结
- 用TreeSet集合存储自定义对象,带参构造方法使用的是比较器排序对元素进行排序
- 比较器排序就是让集合构造方法接收Comparator的实现对象,重写compare(T o1,T 02)方法
- 重写方法时要按照需求来写



