Comparable相当于“内部比较器”,而Comparator相当于“外部比较器”。 1 2 3 4 5 6 7 8 //Comparable example: Collections.sort(list); //Comparator example: // 通过“比较器(AscAgeComparator)”,对list进行排序, AscAgeComparator的排序方式是:根据“age”的升序排序 Collections.sort(list, new AscAgeComp...
Comparator (全限定名 java.util.Comparator) 接口于 Comparable 接口在名字看上去有点相似,主要是两个英文单词的拼写有些类似,容易混淆,其实两者表达的意思从命名上也能看出来,Comparable -- 形容词意思是可比较的,用于修饰对象;Comparator--名词意思是比较器,所以在记忆这两个接口时,可以借助英文里两个单词词性的不...
publicclassListSortExample{publicstaticvoidmain(String[]args){// 创建并初始化 ListList<Person>list=newArrayList<Person>(){{add(newPerson(1,30,"北京"));add(newPerson(2,20,"西安"));add(newPerson(3,40,"上海"));}};// 使用 Comparable 自定的规则进行排序Collections.sort(list);// 打印 list...
in most real-life scenarios, we want sorting based on different parameters. For example, as a CEO, I would like to sort the employees based on Salary, an HR would like to sort them based on age. This is the situation where we need to useJava Comparatorinterface becauseComparable.compareTo...
Comparator 和 Comparable 的排序方法是不同的,Comparable 排序的方法是 compareTo,而 Comparator 排序的方法是 compare,具体实现代码如下: importlombok.Getter;importlombok.Setter;importjava.util.ArrayList;importjava.util.Collections;importjava.util.Comparator;importjava.util.List;publicclassComparatorExample{publicst...
1 Comparable 接口 Comparable接口定义如下: package java.lang; public interface Comparable<T> { public int compareTo(T o); } compareTo()方法用于比较当前对象与指定对象的先后顺序,其可以返回正整数、0、负整数三种数值,分别表示当前对象大于、等于、小于指定对象。若一个类未实现Comparable接口,则使用Arrays....
1 Comparable 接口 Comparable接口定义如下: packagejava.lang; publicinterfaceComparable<T>{ publicintcompareTo(T o); } compareTo()方法用于比较当前对象与指定对象的先后顺序,其可以返回正整数、0、负整数三种数值,分别表示当前对象大于、等于、小于指定对象。若一个类未实现Comparable接口,则使用Arrays.sort()或...
2.使用Comparable接口来排序: 先要改造User类: package com.example.testcomparator; public class User implements Comparable<Object>{ private String name; private int age; public User(String name, int age) { = name; this.age = age; } public int getAge() { ...
Comparable.javapublic interface Comparable<T> { public int compareTo(T o); } For example, for Employee class, the natural ordering can be based on the id field. Employee.javaimport java.time.LocalDate; public class Employee implements Comparable<Employee> { private Long id; private String name...
在上面的示例中,GenericComparator比较器可以用于比较实现了Comparable接口的任何对象。 Lambda 表达式比较器 从Java 8 开始,我们可以使用 Lambda 表达式更简洁地创建比较器。例如,要对字符串按长度进行排序,可以使用 Lambda 表达式: 代码语言:javascript 代码运行次数:0 ...