集合中按照商品价格排序,按照学生编号排序,Collections集合里的sort方法,Comparator接口,Comparable接口,
程序员文章站
2024-01-14 09:55:22
...
Collections 有一个sort方法,查看API文档
学生类:
public class Product implements Comparable<Product>{
private int p_id;
private String p_name;
private float price;
public Product(int p_id, String p_name, float price) {
super();
this.p_id = p_id;
this.p_name = p_name;
this.price = price;
}
public int compareTo(Product o) {
if(this.p_id>o.p_id) return 1;
else if(this.p_id<o.p_id) return -1;
else return 0;
}
}
测试类 按照学生id排序
public class Product implements Comparable<Product>{
private int p_id;
private String p_name;
private float price;
public Product(int p_id, String p_name, float price) {
super();
this.p_id = p_id;
this.p_name = p_name;
this.price = price;
}
public int compareTo(Product o) {
if(this.p_id>o.p_id) return 1;
else if(this.p_id<o.p_id) return -1;
else return 0;
}
}