public interface Comparable {
int compareTo(Object o);
}
----------
public interface Comparator {
int compare(Object o1,Object o2);
}
----------
public class Arrays {
public static void sort(Comparable[] c){
Comparable temp;
for(int i=0;i<c.length;i++){
for(int j=i+1;j<c.length;j++){
if(c[i].compareTo(c[j])>0){
temp = c[i];
c[i] = c[j];
c[j] = temp;
}
}
}
}
}
----------
public class Cat implements Comparable{
private int weight;
private int height;
public Cat(int weight, int height) {
this.weight = weight;
this.height = height;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
/*未使用Comparator接口
* @Override
public int compareTo(Object o) {
if(o instanceof Cat ){
Cat c = (Cat)o;
if(this.height > c.getHeight())
return 1;
if(this.height == c.getHeight())
return 0;
if(this.height < c.getHeight())
return -1;
}
return -10;
}*/
//使用Comparator接口
@Override
public int compareTo(Object o) {
return new HeightComparator().compare(this, o);
}
@Override
public String toString() {
return "("+this.height+"|"+this.weight+")";
}
}
----------
class HeightComparator implements Comparator{
@Override
public int compare(Object o1, Object o2) {
Cat c1=(Cat)o1;
Cat c2=(Cat)o2;
if(c1.getHeight() > c2.getHeight())
return 1;
if(c1.getHeight() == c2.getHeight())
return 0;
if(c1.getHeight() < c2.getHeight())
return -1;
return -10;
}
}
----------
import org.junit.Test;
public class ArraysTest {
@Test
public void testSort() {
Cat[] cats = {new Cat(1,1),new Cat(3,3),new Cat(2,2)};
Arrays.sort(cats);
for(int i=0;i<cats.length;i++){
System.out.print(cats[i]);
}
}
}
Strategy
最新推荐文章于 2024-05-31 11:33:34 发布