<3>比较器Comparator的使用
【摘要】 <3>比较器Comparator的使用我们可以使用比较器实现与自然排序一样的效果。参考来源:JDK APITreeSet(Comparator<? super E> comparator)构造一个新的空 TreeSet,它根据指定比较器进行排序。具体通过代码举例//Student类package java_practice;public class Student { private...
<3>比较器Comparator的使用
我们可以使用比较器实现与自然排序一样的效果。
参考来源:JDK API
TreeSet(Comparator<? super E> comparator)
构造一个新的空 TreeSet,它根据指定比较器进行排序。
具体通过代码举例
//Student类
package java_practice;
public class Student {
private int age;
private String name;
public Student(int age, String name) {
this.age = age;
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
// @Override
// public int compareTo(Student s) {
// int num = this.age -s.age;
// int num2 = num == 0?this.name.compareTo(s.name):num;
// return num2;
}
//测试类
package java_practice;
import java.util.Comparator;
import java.util.TreeSet;
public class TreeSetDemo1 {
public static void main(String args[]) {
TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int num = s1.getAge() - s2.getAge();
int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;
return num2;
}
});
Student s1 = new Student(29, "西施");
Student s2 = new Student(28, "王昭君");
Student s3 = new Student(30, "貂蝉");
Student s4 = new Student(33, "杨玉环");
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
for (Student s : ts) {
System.out.println(s.getName() + "" + s.getAge());
}
}
}
这里实现比较器,是通过匿名内部类实现了。
TreeSet的好多常规方法上面集合中都有包含,所以不再赘述。
后记:单列集合的相关总结一部分来自自己的查阅API方法尝试,一部分是课程笔记。基础比较多,作为学习记录。还有很多没有写进来的知识,如果想起。会添加进来。
文章三万字,内容可能比较杂乱,有不对的地方希望指正。文章一直更新,动态变换。记录的意义在于思维总结,后续的查看,同样为了分享,仅此而已。
【版权声明】本文为华为云社区用户原创内容,未经允许不得转载,如需转载请自行联系原作者进行授权。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)