接口Comparable
public interface Comparable<T>{ int compareTo(T t); }
1. 对称性:sgn(x.compareTo(y)) == -sgn(y.compareTo(x))
2. 传递性: x.compareTo(y) > 0 && y.compareTo(z) > 0, 则x.compareTo(z) > 0
3. 对等性:x.compareTo(y) ==0 则 sgn(x.compareTo(z)) == sgn(y.compareTo(z));
另外,建议如果x.compareTo(y)==0 则 x.equals(y)
TreeSet、TreeMap以及Collections, Arrays会比较依赖Comparable接口,特别是一些搜索和排序算法。
以下是一个比较高效的comparable接口实现例子,利用compareTo 返回int并非必须是0, 1, -1的特性,实现比较接口:
public class City implements Comparalble<City>{ private int provinceCode; private int cityCode; // .... @Override public int compareTo(City c){ int difProv = provinceCode = c.getProvinceCode(); if(difProv !=0){ return diffProv; } return cityCode - c.getCityCode(); } }