Comparable Comparator 比较对象的大小
1,String ,包装类等,实现了Comparable接口,重写compareTo();方法实现对象比较,从小到大排序 2.重写compareTo()规则 1.当对象this 大于形参obj 时候返回正整数, 2.当对象this 小于形参obj 时候返回负整数, 3.当对象this 等于形参obj 时候返回0, 3.对于自定义类,如果要实现对象比较大小,那么实现Comparable,重写compareTo();方法
String[] strarr = {"aa", "cc", "kk", "dd", "bb", "yy"};
Arrays.sort(strarr);
System.out.println(Arrays.toString(strarr));//[aa, bb, cc, dd, kk, yy]
自定义类
class Goods implements Comparable{
private String name;
private double price;
public Goods(){}
public Goods(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public String toString() {
return this.name +" 价格:"+price;
}
/* 重写compareTo()规则
1.当对象this 大于形参obj 时候返回正整数,
2.当对象this 小于形参obj 时候返回负整数,
3.当对象this 等于形参obj 时候返回0,*/
@Override
public int compareTo(Object o) {
if (o instanceof Goods) {
Goods g = (Goods) o;
if(this.price> g.price){
return 1;
} else if (this.price < g.price) {
return -1;
}else {
return 0;
}
}
throw new RuntimeException("输入的价格有误");
}
public static void main(String[] args) {
Goods[] arr = new Goods[4];
arr[0] = new Goods("联想", 23.9);
arr[1] = new Goods("戴尔", 55);
arr[2] = new Goods("神州", 63.6);
arr[3] = new Goods("苹果",33.2);
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
}
实现了comparable不方便修改代码,或者实现comparale 接口的排序不能满足当前需求,那么考虑实现comparator来自定义对象排序
com'pare(object obj,object obj2):比较obj1和obj2的大小
如果返回正整数,表示 obj1大
如果返回负整数,表示obj2大
返回0,表示相等;
public static void main(String[] args) {
String[] strarr = {"aa", "cc", "kk", "dd", "bb", "yy"};
Arrays.sort(strarr, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return -o1.compareTo(o2);
}
});
System.out.println(Arrays.toString(strarr));
}
自定义类使用comparator
class Goods implements Comparable {
private String name;
private double price;
public Goods() {
}
public Goods(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public String toString() {
return this.name + " 价格:" + price;
}
@Override
public int compareTo(Object o) {
if (o instanceof Goods) {
Goods g = (Goods) o;
return Double.compare(this.price, g.price);
}
throw new RuntimeException("输入数据有误");
}
public static void main(String[] args) {
Goods[] arr = new Goods[6];
arr[0] = new Goods("联想", 23.9);
arr[1] = new Goods("戴尔", 55);
arr[2] = new Goods("神州", 63.6);
arr[3] = new Goods("苹果",33.2);
arr[4] = new Goods("苹果",53.2);
arr[5] = new Goods("苹果",93.2);
Arrays.sort(arr, new Comparator<Goods>() {
@Override
public int compare(Goods o1, Goods o2) {
if (o1.name.equals(o2.name)) {
//名字相同 价格从大到小
return -Double.compare(o1.price, o2.price);
} else {
//价格不相同按名字排序
return o1.name.compareTo(o2.name);
}
}
});
System.out.println(Arrays.toString(arr));
}
}
//values() 获取枚举对象列表
Season[] seasons = Season.values();
for (Season s:seasons){
System.out.println(s);
}
//valueof(String objName) 通过名称获取对应的枚举对象
Season season2 = Season.valueOf("WINTER");
System.out.println(season2);