1 Comparable(自然排序)
一般是类实现Comparale接口,然后重写CompareTo方法,之后使用Array.Sort()时即可实现排序
- 重点就是在重写compareTo方法时所要遵循的原则:
this对象 > 形参对象 返回正数
this对象 < 形参对象 返回负数
this对象 = 形参对象 返回0
重写方法只需要完成这个逻辑,之后调用Array.Sort会自动进行排序
package com.yal.thread1;
public class DateTest {
public static void main(String[] args) {
goods[] array = new goods[4];
array[0] = new goods("cianxiang",234);
array[1] = new goods("buawei",234);
array[2] = new goods("d",3);
array[3] = new goods("o",53);
System.out.println(Arrays.toString(array));
System.out.println("-------------");
Arrays.sort(array);
System.out.println(Arrays.toString(array));
}
}
class goods implements Comparable{
//属性
String name;
double price;
//构造器
public goods() {
}
public goods(String name, double price) {
this.name = name;
this.price = price;
}
//get set方法
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 +
'}';
}
//重写的compareTo方法
@Override
public int compareTo(Object o) {
if(o instanceof goods) {
goods s = (goods) o;
if(this.price > s.price){
return 1;
}else if(this.price < s.price){
return -1;
}else{
return this.name.compareTo(s.name);
}
}
throw new RuntimeException("传入数据非法");
}
}
2 Comparator(定制排序)
package com.yal.thread1;
public class DateTest {
public static void main(String[] args) {
goods[] array = new goods[4];
array[0] = new goods("cianxiang",234);
array[1] = new goods("buawei",234);
array[2] = new goods("d",3);
array[3] = new goods("d",53);
System.out.println(Arrays.toString(array));
System.out.println("-----");
//需要的时候,临时实现了Comparator类进行排序
Arrays.sort(array, new Comparator<goods>() {
//实现逻辑 先按照name从低到高排,再按照价格从高到低排
@Override
public int compare(goods o1, goods o2) {
if (o1.getName().equals(o2.getName())) {
if(o1.getPrice() > o2.getPrice()){
return -1;
}else if(o1.getPrice() < o2.getPrice()){
return 1;
}else{
return 0;
}
} else {
return o1.getName().compareTo(o2.getName());
}
}
});
System.out.println(Arrays.toString(array));
}
}
class goods{
String name;
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 +
'}';
}
}
3 两者的异同
Comparable接口的方式一旦一定,接口实现类的对象在任意位置都可以比较大小,而Comparator接口属于临时性的比较