版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/StriverFeng/article/details/52224666
我们都知道在实现把对象存入到集合中,然后再对对象按照自己的方式进行排序,最方便的方法就是让集合中的对象实现Comparable接口,
然后重写 compareTo方法,接下来我把自己的demo拿出来
Student.java:
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 s) {
// 这里返回什么,其实应该根据我的排序规则来做
int num3 =(this.name.equals(s.name)? 0:1);
System.out.println(num3);
return num3;
}
}
public class TreeSetDemo{
public static void main(String[] args) {
// 创建集合对象
TreeSet<Student> ts = new TreeSet<Student>();
// 创建元素
Student s1 = new Student("lin", 27);
Student s2 = new Student("zhang", 29);
Student s3 = new Student("wang", 23);
Student s4 = new Student("linq", 28);
Student s5 = new Student("liu", 21);
Student s6 = new Student("wu", 40);
Student s7 = new Student("feng", 20);
Student s8 = new Student("Feng", 24);
// 添加元素
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
ts.add(s5);
ts.add(s6);
ts.add(s7);
ts.add(s8);
// 遍历
for (Student s : ts) {
System.out.println(s.getName() + "---" + s.getAge());
}
}
}
由于比较好奇它通过compareTo方法进行比较是怎么比较的,所以给了一个输出,最终添加8个student对象,有20次输出
这是最终的输出:
0
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
lin---27
zhang---29
wang---23
linq---28
liu---21
wu---40
feng---20
Feng---24
比较疑惑,防止忘记,mark一下