@Test public void test1(){ Goods[] arr1 = new Goods[5]; arr1[0] = new Goods("lenovoMouse",35); arr1[1] = new Goods("huaweiMouse",65); arr1[2] = new Goods("dellMouse",43); arr1[3] = new Goods("xiaomiMouse",21); arr1[4] = new Goods("mircsoftMouse",65); Arrays.sort(arr1); System.out.println(Arrays.toString(arr1)); }
package com.Tang.StringDay02; public class Goods implements Comparable{ private String name; private double price; public Goods() { } public Goods(String name, int 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 "name='" + name + '\'' + ", price=" + price + '\n'; } //指明商品比较大小的方式:按价格从低到高排序,价格相同按名称从高到低排 @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 -this.name.compareTo(goods.name); //按价格排序方式二 // return Double.compare(this.price,goods.price); } throw new RuntimeException(); } }
@Test public void test3(){ Goods[] arr1 = new Goods[5]; arr1[0] = new Goods("lenovoMouse",35); arr1[1] = new Goods("huaweiMouse",65); arr1[2] = new Goods("dellMouse",43); arr1[3] = new Goods("huaweiMouse",21); arr1[4] = new Goods("mircsoftMouse",65); //指明商品比较大小的方式:按名称从低到高排序,名称相同按价格从高到低排 Arrays.sort(arr1, 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() == g2.getName()){ return -Double.compare(g1.getPrice(),g2.getPrice()); } else{ return g1.getName().compareTo(g2.getName()); } } throw new RuntimeException("输入数据类型不一致"); } }); System.out.println(Arrays.toString(arr1)); }
运行结果图