一:说明:
Java 中的对象,正常情况下,只能进行比较:== 或!=。不能用>或<的
但是在开发环境中,我们需要对多个对象进行排序,言外之意,需要比较对象的大小 如何实现?使用两个接口中的任何一个:Comparable 和Comparator
二:Comparable接口 和Comparator接口区别?
Java实现对象排序的方式有两种:
public void test1(){
String[] arr = new String[]{"AA","CC","KK","MM","GG","JJ","DD"};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));//[AA, CC, DD, GG, JJ, KK, MM]
}
public class Goods implements Comparable {
private String name;
private double price;
public Goods(){
}
public Goods(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Goods{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
//指明商品比较大小的方式
@Override
public int compareTo(Object o) {
if(o instanceof Goods){
Goods goods = (Goods)o;
//方式一:
if(this.price>goods.price){
return 1;
}else if(this.price<goods.price) {
return -1;
}else{
return 0;
}
//方式二:
// return Double.compare(this.price,goods.price);
}
throw new RuntimeException("传入的数据类型不一致");
}
}
public void test2(){
Goods[] arr = new Goods[4];
arr[0] = new Goods("lenovoMouse",34);
arr[1] = new Goods("dellMouse",53);
arr[2] = new Goods("xiaomiMouse",63);
arr[3] = new Goods("huaweiMouse",39);
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
public void test3(){
String[] arr = new String[]{"AA","CC","KK","MM","GG","JJ","DD"};
Arrays.sort(arr, new Comparator() {
//按照字符串从大到小的顺序排列
@Override
public int compare(Object O1, Object O2) {
if(O1 instanceof String && O2 instanceof String){
String s1 =(String) O1;
String s2 =(String) O2;
return -s1.compareTo(s2);
}
//return 0;
throw new RuntimeException("输入的数据类型不一致");
}
});
System.out.println(Arrays.toString(arr));//[AA, CC, DD, GG, JJ, KK, MM]
}
public void test4(){
Goods[] arr = new Goods[4];
arr[0] = new Goods("lenovoMouse",34);
arr[1] = new Goods("dellMouse",53);
arr[2] = new Goods("xiaomiMouse",63);
arr[3] = new Goods("huaweiMouse",39);
Arrays.sort(arr, new Comparator() {
//指明商品比较大小的方式:先按照产品名称从高到低排序,再按照价格从低到高排序,
@Override
public int compare(Object o1, Object o2) {
if(o1 instanceof Goods && o2 instanceof Goods) {
Goods g1 = (Goods) o1;
Goods g2 = (Goods) o2;
if(g1.getName().equals(g2.getName())){
return Double .compare(g1.getPrice(),g2.getPrice());
}else{
return g1.getName().compareTo(g2.getName());
}
}
throw new RuntimeException("输入的数据类型不一致");
}
});
System.out.println(Arrays.toString(arr));
}