1、Product类
1 public class Product 2 { 3 private int pid; 4 private String name; 5 private double price; 6 7 public Product() 8 { 9 // TODO Auto-generated constructor stub 10 } 11 12 public Product(int pid, String name, double price) 13 { 14 this.pid = pid; 15 this.name = name; 16 this.price = price; 17 } 18 19 public int getPid() 20 { 21 return pid; 22 } 23 24 public void setPid(int pid) 25 { 26 this.pid = pid; 27 } 28 29 public String getName() 30 { 31 return name; 32 } 33 34 public void setName(String name) 35 { 36 this.name = name; 37 } 38 39 public double getPrice() 40 { 41 return price; 42 } 43 44 public void setPrice(double price) 45 { 46 this.price = price; 47 } 48 49 }
2、类比较器:重写compare方法
1 public class MyCompare implements Comparator<Product> // 泛型<Product>表示该比较器只能比较Product类型 2 { 3 4 @Override 5 public int compare(Product p1, Product p2) 6 { 7 if (p1.getPrice() < p2.getPrice()) 8 { 9 return -1; 10 } 11 else if (p1.getPrice() > p2.getPrice()) 12 { 13 return 1; 14 } 15 else 16 // 如果价格一样,按照id排序 17 { 18 if (p1.getPid() < p2.getPid()) 19 { 20 return -1; 21 } 22 else if (p1.getPid() > p2.getPid()) 23 { 24 return 1; 25 } 26 else 27 { 28 return 0; 29 } 30 } 31 } 32 33 }
3、在ArrayList中使用比较器
1 public class ProductSort 2 { 3 public static void main(String[] args) 4 { 5 6 Product p1 = new Product(1, "爆米花手机", 1000000.00); 7 Product p2 = new Product(2, "iPhone 7s", 5088.00); 8 Product p3 = new Product(3, "小米5s", 1999.99); 9 Product p4 = new Product(4, "NIIT课程", 12800.00); 10 Product p5 = new Product(5, "百达翡丽", 1980000.00); 11 Product p6 = new Product(6, "宝玛electric", 1999.99); 12 Product p7 = new Product(7, "TIIN课程", 12800.00); 13 // 获得数组准备排序 14 Product[] proArr = { p1, p2, p3, p4, p5, p6, p7 }; 15 16 Arrays.sort(proArr, new MyCompare()); 17 18 for (Product p : proArr) 19 { 20 System.out.println(p.getPid() + " " + p.getName() + " " 21 + p.getPrice()); 22 } 23 } 24 }
时间: 2024-10-05 18:51:10