本文共 2850 字,大约阅读时间需要 9 分钟。
package cn.edu.hpu.Strategy;//interface类里面的方法默认都是publicpublic interface Comparator { /*实现这个接口的对象使用这个方法进行比较时, *返回1是比那个对象大,返回0是相等,返回-1是比那个对象小*/ int compare(Object o1,Object o2);}我们之前对狗进行的是利用高度进行排序,现在我们用其重量来比较大小。 我们重新创建一个类,叫做"狗的根据重量的比较器",它去实现Comparator接口
package cn.edu.hpu.Strategy;public class DogWeightComparator implements Comparator{ @Override public int compare(Object o1, Object o2) { Dog d1=(Dog)o1; Dog d2=(Dog)o2; if(d1.getWeight()>d2.getWeight()) return 1; else if(d1.getWeight()对于狗来说,我们之前实现Comparable接口了,此时比较逻辑不要在comparaTo()方法中写死,我们在comparaTo()中new出一个DogWeightComparator比较器,来比较当前的对象和传进来的对象的大小。
package cn.edu.hpu.Strategy;public class Dog implements Comparable{ //狗的身高 private int height; //狗的体重 private int weight; public Dog(int height, int weight) { super(); this.height = height; this.weight = weight; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } @Override public int compareTo(Object o) { return new DogWeightComparator().compare(this, o); } @Override public String toString() { return this.getHeight()+"|"+this.getWeight(); } }这个时候你就会发现好处:假如我对重量比较不满意了,我可以换成new别的来实现别的比较方法。 我们最好设置一个成员变量,是比较器Comparator类型的,设好它的get和set方法,具体向里面放什么样的比较器,我们在comparaTo()方法中就引用什么样的比较器来比较大小。
package cn.edu.hpu.Strategy;public class Dog implements Comparable{ //狗的身高 private int height; //狗的体重 private int weight; //比较器(默认指定DogWeightComparator) private Comparator comparator=new DogWeightComparator(); public Dog(int height, int weight) { super(); this.height = height; this.weight = weight; } public Comparator getComparator() { return comparator; } public void setComparator(Comparator comparator) { this.comparator = comparator; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } @Override public int compareTo(Object o) { return comparator.compare(this, o); } @Override public String toString() { return this.getHeight()+"|"+this.getWeight(); } }测试:
package cn.edu.hpu.Strategy;public class Test { public static void main(String[] args) {; Dog[] dogs={new Dog(3,8),new Dog(5,4),new Dog(1,2)}; DataSorter.sort(dogs); DataSorter.p(dogs); }}结果: 1|2 5|4 3|8 我们发现使用狗的重量来排序了。 当我们使用新创建的Comparator接口的时候,你会发现世界又美好了一些,因为我写完一个Dog类之后我还可以跟着设置他们两个对象之间的比较方式,这样我们类的扩展能力就更强了。 大家仔细想想Comparable、Comparator接口与DataSorter和比较类Dog、Cat之间的关系,就会总结出Comparator接口出现的好处。
下一篇总结收尾。
转载请注明出处: