compareble
- compareble默认比较
- comparetor新建比较器
比较器
类:public class Product implements Comparable{
private int id;
private String p_name;
private float p_price;
public Product() {
super();
}
public Product(int id, String p_name, float p_price) {
super();
this.id = id;
this.p_name = p_name;
this.p_price = p_price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getP_name() {
return p_name;
}
public void setP_name(String p_name) {
this.p_name = p_name;
}
public float getP_price() {
return p_price;
}
public void setP_price(float p_price) {
this.p_price = p_price;
}public int compareTo(Product o) {
if (this.id>o.id) {
return 1;
}else if (this.id==o.id) {
return 0;
}else {
return -1;
}
}
}
-按name排序的类:import java.util.Comparator;
public class ProductsCompareByP_Name implements Comparator{
@Override
public int compare(Product o1, Product o2) {
// TODO Auto-generated method stub
return o1.getP_name().compareTo(o2.getP_name());
}
}
- 按price排序的方法:import java.util.Comparator;
public class ProductsCompareByP_Price implements Comparator {
@Override
public int compare(Product o1, Product o2) {
if (o1.getP_price()>o2.getP_price()) {
return 1;
}else if (o1.getP_price()==o2.getP_price()) {
return 0;
}else {
return -1;
}
}
}
- 测试:import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class PruductTest {
public static void main(String[] args) {
ArrayList<Product> products=new ArrayList<Product>();
Product product1=new Product(6,"薯片",3);
Product product2=new Product(7,"可乐",2.5f);
Product product3=new Product(8,"辣条",3.5f);
Product product4=new Product(9,"瓜子",5);
products.add(product1);
products.add(product2);
products.add(product3);
products.add(product4);
System.out.println("**********展示商品列表***************");
for (Product n:products) {
System.out.println(n.getId()+"\t"+n.getP_name()+"\t"+n.getP_price());
}
System.out.println("***********展示完成*******************");
System.out.println("\n请选择排序方式:\n1、按商品Id排序\t2、按商品名称排序\t3、按商品的价格排序");
Scanner scanner=new Scanner(System.in);
int ordertype=scanner.nextInt();
switch (ordertype) {
case 1:
Collections.sort(products);
break;
case 2:
ProductsCompareByP_Name pByP_Name=new ProductsCompareByP_Name();
Collections.sort(products, pByP_Name);
break;
case 3:
ProductsCompareByP_Price pByP_Price= new ProductsCompareByP_Price();
Collections.sort(products, pByP_Price);
break;
default:
System.out.println("请按套路出牌");
break;
}
if (ordertype==1||ordertype==2||ordertype==3) {
System.out.println("排序后的列表");
for (Product n:products) {
System.out.println(n.getId()+"\t"+n.getP_name()+"\t"+n.getP_price());
}
}
}
}