Java实现对象排序的方式有两种:
- 自然排序:java.lang.Comparable
- 定制排序:java.util.Comparator
方式一:自然排序:java.lang.Comparable
- Comparable接口强行对实现它的每个类的对象进行整体排序。这种排序被称为类的自然排序。
- 实现 Comparable 的类必须实现 compareTo(Object obj) 方法,两个对象即通过 compareTo(Object obj) 方法的返回值来比较大小。如果当前对象this大 于形参对象obj,则返回正整数,如果当前对象this小于形参对象obj,则返回负整数,如果当前对象this等于形参对象obj,则返回零。
- 实现Comparable接口的对象列表(和数组)可以通过 Collections.sort 或Arrays.sort进行自动排序。实现此接口的对象可以用作有序映射中的键或有序集合中的元素,无需指定比较器。
public class ComparableTest {
public static void main(String[] args) {
Good[] goods = new Good[4];
goods[0] = new Good(3, "aaa");
goods[1] = new Good(6, "haa");
goods[2] = new Good(2, "aa9");
goods[3] = new Good(6, "a7a");
Arrays.sort(goods);
System.out.println(Arrays.toString(goods));
}
}
class Good implements Comparable {
double price;
String name;
public Good(double price, String name) {
this.price = price;
this.name = name;
}
@Override
public String toString() {
return "Good{" +
"price=" + price +
", name='" + name + '\'' +
'}';
}
@Override
public int compareTo(Object o) {
if (o instanceof Good) {
Good other = (Good) o;
if (this.price > ((Good) o).price) {
return 1;
} else if (this.price < ((Good) o).price) {
return -1;
} else if (this.price == ((Good) o).price) {
return 0;
}
}
throw new RuntimeException("输入类型不一致");
}
}
方式二:定制排序:java.util.Comparator
public class ComparableTest1 {
public static void main(String[] args) {
Good1[] good1s = new Good1[4];
good1s[0] = new Good1(12,"java");
good1s[1] = new Good1(10,"c++");
good1s[2] = new Good1(2,"c");
good1s[3] = new Good1(19,"java");
Arrays.sort(good1s, new Comparator<Good1>() {
@Override
public int compare(Good1 o1, Good1 o2) {
if (o1 instanceof Good1){
Good1 g1 = (Good1) o1;
Good1 g2 = (Good1) o2;
return g1.getName().compareTo(g2.getName());
}
throw new RuntimeException("比较错误");
}
});
System.out.println(Arrays.toString(good1s));
}
}
class Good1 {
private double price;
private String name;
public Good1() {
}
public Good1(double price, String name) {
this.price = price;
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Good1{" +
"price=" + price +
", name='" + name + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Good1 good1 = (Good1) o;
return Double.compare(good1.price, price) == 0 && Objects.equals(name, good1.name);
}
@Override
public int hashCode() {
return Objects.hash(price, name);
}
}
结果:[Good1{price=2.0, name='c'}, Good1{price=10.0, name='c++'}, Good1{price=12.0, name='java'}, Good1{price=19.0, name='java'}]