集合中按照商品价格排序,按照学生编号排序,Collections集合里的sort方法,Comparator<T>接口,Comparable<T>接口,

来源:互联网 发布:linux启动卡在进度条 编辑:程序博客网 时间:2024/06/05 16:58

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;}}





阅读全文
1 0