public class Good implements Comparable{
private int id;
private String name;
private double price;
public Good(int id, String name, double price) {
super();
this.id = id;
this.name = name;
this.price = price;
}
public double getPrice() {
return price;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("商品");
builder.append(id);
builder.append("号: 名称 ");
builder.append(name);
builder.append(", 价格 ");
builder.append(price);
return builder.toString();
}
@Override
public int compareTo(Object o) {
Good other = (Good) o;
if(this.price != other.price) {
return Double.compare(this.price, other.price);
}
return 0;
}
}
package Test01;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ShoppingCart {
private List<Good> list = new ArrayList<Good>();
public void addGoods(Good good) {
list.add(good);
}
public void sortByPriceFromLowToHigh01() {
System.out.println("\n使用 法一 排序中。。。");
Collections.sort(this.list);
System.out.println("============商品排序结束============");
}
public void sortByPriceFromLowToHigh02() {
System.out.println("\n使用 法二 排序中。。。");
Collections.sort(this.list, new GoodsPriceComparator());
System.out.println("============商品排序结束============");
}
public void PrintGoods() {
System.out.println("当前购物车中顺序是:");
for (Good good : list) {
System.out.println(good);
}
}
public static void main(String[] args) {
ShoppingCart shoppingCart = new ShoppingCart();
shoppingCart.addGoods(new Good(1, "OPPOR13", 1999));
shoppingCart.addGoods(new Good(3, "卫龙麻辣条", 0.5));
shoppingCart.addGoods(new Good(4, "红豆保暖裤", 19));
System.out.println("============商品添加完毕============");
shoppingCart.PrintGoods();
shoppingCart.sortByPriceFromLowToHigh01();
shoppingCart.PrintGoods();
shoppingCart.sortByPriceFromLowToHigh02();
shoppingCart.PrintGoods();
}
}