package cn.edu.hpu.Strategy; //interface类里面的方法默认都是public public interface Comparator { /*实现这个接口的对象使用这个方法进行比较时, *返回1是比那个对象大,返回0是相等,返回-1是比那个对象小*/ int compare(Object o1,Object o2); }
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()<d2.getWeight()) return -1; return 0; } }
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(); } }
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); } }
下一篇总结收尾。
转载请注明出处:http://blog.csdn.net/acmman/article/details/46634565