接口说明
接口名称 | 包 | 主要函数 | 函数作用 |
---|---|---|---|
Comparable | java.lang | int compareTo(T o) | 比较此对象与指定对象的顺序 |
Comparator | java.util | int compare(T o1,T o2) | 比较用来排序的两个参数 |
Comparable接口
接口返回值为int类型
int compareTo(T o);
int == 0
表示此对象与指定对象相等
int>0
表示此对象大于指定对象
int<0
表示此对象小于指定对象
抛出: CalssCastException - 如果指定对象的类型不允许它与此对象进行比较
示例:
package com.wind.strategy;
import java.util.*;
import java.lang.*;
public class Dog implements Comparable {
Integer w;
Integer h;
public Dog(Integer w, Integer h) {
this.w = w;
this.h = h;
}
@Override
public String toString() {
return "Dog{" +
"w=" + w +
", h=" + h +
'}';
}
@Override
public int compareTo(Object o) {
Dog d = (Dog)o;
return this.h-d.h;
}
public static void main(String[] args) {
List<Dog> list = new ArrayList<Dog>();
list.add(new Dog(5,5));
list.add(new Dog(5,1));
list.add(new Dog(5,3));
Collections.sort(list); //集合排序方法
list.forEach(f-> System.out.println(f));
}
}
输出结果
Comparator接口
接口返回值为int类型
int compare(T o1,T o2);
int == 0
表示o1==o2
int>0
表示o1>o2
int<0
表示o1<o2
示例:
import java.util.*;
import java.lang.*;
public class Dog {
Integer w;
Integer h;
public Dog(Integer w, Integer h) {
this.w = w;
this.h = h;
}
@Override
public String toString() {
return "Dog{" +
"w=" + w +
", h=" + h +
'}';
}
public static void main(String[] args) {
List<Dog> list = new ArrayList<Dog>();
list.add(new Dog(5,5));
list.add(new Dog(5,1));
list.add(new Dog(5,3));
Collections.sort(list, new Comparator<Dog>() {
@Override
public int compare(Dog o1, Dog o2) {
return o1.h-o2.h;
}
}); //集合排序方法
list.forEach(f-> System.out.println(f));
}
}
输出结果