首先第一种:
1、通过编写一个类来实现Comparable这个接口;
2、重写里面的comparaTo这个方法;{
方法体中自定义一些自己的比较规则;
}
下面展示一些 内联代码片
。
public class Student implements Comparable<Student> {
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;
}
@Override
public int compareTo(Student o) {
return this.age-o.age; //按年龄排序
}
}
第二种方式:
1、编写一个自定义类来实现Comparator这个接口;
2、实现里面的compara方法;
3、在我们创建集合的时候,创建出自定义类的实例,放入到创建集合的参数中去;
下面展示一些 内联代码片
。
class MyComparator implements Comparator<String>{
@Override
public int compare(Student o1, Student o2) {
return o2.getAge()- o1.getAge();//降序排列
}
Set set = new TreeSet(new MyComparator())
Student s1 = new Student("张三",3);
Student s2 = new Student("李四",4);
Student s3 = new Student("王五",5);
set.add(s1);
set.add(s2);
set.add(s3);
......