从优先价格,其次点击量,最后商品名称排序
实现java.lang.Comparable
package GoodsSort;
public class Goods implements java.lang.Comparable<Goods> {
private int price;//商品价格
private String name;//商品名称
int mouse;//商品点击量
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMouse() {
return mouse;
}
public void setMouse(int mouse) {
this.mouse = mouse;
}
public Goods(int price, String name, int mouse) {
super();
this.price = price;
this.name = name;
this.mouse = mouse;
}
public Goods() {
super();
}
@Override
public String toString() {
return "商品是:" + getName() + ",价格" + getPrice() + ", 点击量为" + getMouse() + "\n";
}
/***
* 重写compareTo
* 按照业务规则,先比较点击量,点击量相等在比较商品价格,最后比较商品名
*
* @param g
* @return
*/
public int compareTo(Goods g){
int result = 0;
if(0 == result){
result =-(this.mouse - g.mouse);//-升序(降序)
if(0 == result){
result = -(this.price - g.price);//降序
}if(0 == result){
result = -(this.name.compareTo(g.name));//降序
}
}
return result;
}
}
自己实现一个,方便应对各种排序规则
package GoodsSort;
public class Goods {
private int price;//商品价格
private String name;//商品名称
int mouse;//商品点击量
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMouse() {
return mouse;
}
public void setMouse(int mouse) {
this.mouse = mouse;
}
public Goods(int price, String name, int mouse) {
super();
this.price = price;
this.name = name;
this.mouse = mouse;
}
public Goods() {
super();
}
@Override
public String toString() {
return "商品是:" + getName() + ",价格" + getPrice() + ", 点击量为" + getMouse() + "\n";
}
}
package GoodsSort;
/***
* 按照业务规则:价格进行排序[降序]
* @author zw
*
*/
public class GodsPrice implements java.util.Comparator<Goods> {
@Override
public int compare(Goods o1, Goods o2) {
return -(o1.getPrice()-o2.getPrice()>0?1:o1.getPrice()-o2.getPrice()==0?0:-1);//默认为升序,前面加负号为降序
}
}
package GoodsSort;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class TestGoods {
public static void main(String[] args){
List<Goods> list = new ArrayList<Goods>();
list.add(new Goods(120,"java实战开发经典100例",1500));
list.add(new Goods(150,"java从入门到放弃",3000));
list.add(new Goods(120,"java基础",1800));
list.add(new Goods(180,"java高级语言",3500));
list.add(new Goods(150,"c++入门",1000));
System.out.println("排序前:"+list);
Collections.sort(list,new GodsPrice());
System.out.println("##########价格排序###############");
System.out.println("按照价格排序后:\n"+list);
}
}