一、Comparable 自然排序
类实现java.lang.Comparable接口,重写compareTo方法,返回int型
package test;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
Computer[] computers = new Computer[4];
computers[0] = new Computer("Apple",10000.00);
computers[1] = new Computer("Huawei",8000.00);
computers[2] = new Computer("Dell",7000.00);
computers[3] = new Computer("Lenovo",9000.00);
if(computers[1].compareTo(computers[2]) > 0){
System.out.println("computer1更贵");
}else {
System.out.println("computer2更贵");
}
Arrays.sort(computers);
for (Computer c: computers) {
System.out.println(c.getBrandName()+": ¥"+c.getPrice());
}
}
}
class Computer implements Comparable{
private String brandName;
private double price;
@Override
public int compareTo(Object o) {
Computer c = null;
if (o instanceof Computer){
c = (Computer)o;
}else {
throw new RuntimeException("对象类型错误");
}
return (int) (this.price-c.getPrice());
}
public Computer(String brandName, double price) {
this.brandName = brandName;
this.price = price;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
// 输出:
computer1更贵
Dell: ¥7000.0
Huawei: ¥8000.0
Lenovo: ¥9000.0
Apple: ¥10000.0
二、Comparetor定制排序,临时使用
package test;
import java.util.Arrays;
import java.util.Comparator;
public class Test {
public static void main(String[] args) {
Computer[] computers = new Computer[4];
computers[0] = new Computer("Apple",10000.00);
computers[1] = new Computer("Huawei",8000.00);
computers[2] = new Computer("Dell",7000.00);
computers[3] = new Computer("Lenovo",9000.00);
System.out.println("********按品牌首字母升序********");
Arrays.sort(computers, new Comparator<Computer>() {
@Override
public int compare(Computer o1, Computer o2) {
return o1.getBrandName().charAt(0)-o2.getBrandName().charAt(0);
}
});
for (Computer c: computers) {
System.out.println(c.getBrandName()+": ¥"+c.getPrice());
}
System.out.println("********按品牌价格降序********");
Arrays.sort(computers, new Comparator<Computer>() {
@Override
public int compare(Computer o1, Computer o2) {
return (int) (o2.getPrice()-o1.getPrice());
}
});
for (Computer c: computers) {
System.out.println(c.getBrandName()+": ¥"+c.getPrice());
}
}
}
class Computer {
private String brandName;
private double price;
public Computer(String brandName, double price) {
this.brandName = brandName;
this.price = price;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
// 输出:
********按品牌首字母升序********
Apple: ¥10000.0
Dell: ¥7000.0
Huawei: ¥8000.0
Lenovo: ¥9000.0
********按品牌价格降序********
Apple: ¥10000.0
Lenovo: ¥9000.0
Huawei: ¥8000.0
Dell: ¥7000.0