为了让类的对象间可以排序,通常有两种方法——Comparable<T> 与 Comparator<T>。
为了判断两个对象是否相等与Set中去重,通常重写根类的equals()方法。
为了逻辑一致:
强烈建议重写comparableTo()后也重写equals()方法。
Comparable泛型接口
int java.lang.Comparable.
compareTo(T o)
本对象与参数进行对比。返回为负表示小于,零表示相等,正数表示大于。
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
本对象与参数进行对比。返回为负表示小于,零表示相等,正数表示大于。
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
Comparator泛型接口
int StudentComparator.
compare(Student o1, Student o2)
返回值约定同Comparable泛型接口。
当一个类没有实现Comparable接口而又希望对它排序时,可以用Comparator。
<Object> Comparator<Object> java.util.Collections.
reverseOrder()
返回一个comparator,它的规则是自然顺序的倒序。自然顺序与类继承的Comparable接口实现有关。通常用于List的从大到小排列。
Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
返回一个comparator,它的规则是自然顺序的倒序。自然顺序与类继承的Comparable接口实现有关。通常用于List的从大到小排列。
Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
equals()重写
equals(Object obj)是Object类的方法,实现见下:
//Object.java
public boolean equals(Object obj) {
return (this == obj);
}
对于自定义的类,可重写此方法达到想要的目的。可参照JDK中String类的equals方法:
如果一个类已经有了compareTo()方法,就可以这么写:
@Override
public boolean equals(Object obj) {
return compareTo((E)obj)==0;
}
然后,对于自定义的类,就可以这样调:
public class BWGRecheckRequest {
//'online' or 'h5' or 'app'
public String source;
//'ip' or 'clientid'
public String keyType;
//accurate ip or clientid
public String theKey;
//flight,hotel,tuan,and so on
public String channel;
@Override
public int hashCode() {
return MyEqualsUtil.hashCode(this);
}
@Override
public boolean equals(Object obj) {
return MyEqualsUtil.equals(this, obj);
}
}