1 方法1:实现Comparable接口
package yangzp.compareable;
/**
* @author yzp
*/
public class ComparableTest {
//在这会报错,因为我传入的不是同一类型的两个类
//我在下边抛出了错误 throw
public static void main(String[] args) {
Student s = new Student("yzp",20);
Object h = new Object();
Object o = new Student("kk",20);
System.out.println(s.compareTo(h));
}
}
class Student implements Comparable{
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
///。。。。。。。。此处省略了Get And Set。。。。//
@Override
public int compareTo(Object o) {
if (o instanceof Student){
return this.getAge() - ((Student) o).getAge();
}
throw new RuntimeException("该类型不是Student");
}
}
2 方法2 给sort(函数)或者equal函数传入Comparator类
package yangzp.compareable;
import java.util.*;
/**
* @author yzp
*/
public class ComparatorTest {
public static void main(String[] args) {
Goods[] goods = new Goods[5];
goods[0] = new Goods("Coke",30);
goods[1] = new Goods("XueBi",2);
goods[2] = new Goods("FenDa",41);
goods[3] = new Goods("TeLunSu",53);
goods[4] = new Goods("YiLi",24);
Arrays.sort(goods,a);
System.out.println(Arrays.toString(goods));
}
private static Comparator a = new Comparator(){
@Override
public int compare(Object o, Object t1) {
if (o instanceof Goods && t1 instanceof Goods){
return (((Goods) o).getPrice() - ((Goods) t1).getPrice());
}
throw new RuntimeException("传入数据类型不一致");
}
};
}
class Goods{
private String name;
private int price;
public Goods(String name, int price) {
this.name = name;
this.price = price;
}
///。。。。。。。。此处省略了Get And Set。。。。//
@Override
public String toString() {
return "Goods{" +
"name='" + name + ''' +
", price=" + price +
'}';
}
}