目錄
Java提供了一個用於比較的接口Comparator和Comparable接口,提供了一個比較的方法,所有實現該接口的類,都動態的實現了該比較方法。
一、comparator接口
1、list的比較
如果要使用list的sort方法需要實現一個Comparator接口,自定義比較方式
public static void main(String[] args) {
List<Integer> list= new ArrayList<>();
list.add(20);
int i=0;
while (i<10){
list.add(i++);
}
list.sort(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if (o1.intValue()>o2.intValue()){
return 1;
}else if (o1.intValue()<o2.intValue()){
return -1;
}
return 0;
}
});
System.out.println(list.toString());
}
2、數組的比較
同理
Integer[] ins = {3, 5, 1, 6, 7};
Arrays.sort(ins, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if (o1.intValue()>o2.intValue()){
return 1;
}else if (o1.intValue()<o2.intValue()){
return -1;
}
return 0;
}
});
System.out.println(Arrays.toString(ins));
二、Comparable接口
該接口是需要被你所需要排序的類所實現,違反了開閉原則。
需要排序的類實現comparable接口的方法
public class Person implements Comparable<Person> {
public Integer getAge() {
return age;
}
public Person(Integer age){
this.age=age;
}
public void setAge(Integer age) {
this.age = age;
}
private Integer age;
@Override
public int compareTo(Person o) {
return this.age<o.getAge()?1:(this.age==o.getAge()?0:-1);
}
}
public static void main(String[] args) {
Person[] peoples={new Person(20),new Person(50),new Person(10)};
Arrays.sort(peoples);
System.out.println(Arrays.toString(peoples));
}
運行結果
綜合來說使用comparator接口更符合開發原則!!!