list排序

主要用到Collections这个类中的sort方法及Comparator这个接口。

所以我们须要三个类:实体类,比较类(这个类实现)Comparator接口,测试类

//Person类

public class Person {
 private int id;
 private float account;
 private String name;
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public float getAccount() {
    return account;
}
public void setAccount(float account) {
    this.account = account;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
                                                              
}



//ComparatorPserson类,比较类,我们根据用户的帐户的钱来排序

public class ComparatorPserson implements Comparator<Person> {
    public int compare(Person p1, Person p2) {
        float acount1 = p1.getAccount();
        float acount2 = p2.getAccount();
        int a = (int)(acount1 - acount2);
        return a;
    }
}



//测试类

public class Tests {
 public static void main(String[] args) {
    Person p = new Person();
    List<Person> list = new ArrayList<Person>();
    ComparatorPserson cp = new ComparatorPserson();
    p.setId(1);
    p.setAccount(21.6f);
    p.setName("张三");
                                  
    Person p1 = new Person();
    p1.setId(2);
    p1.setAccount(133.3f);
    p1.setName("李四");
                                  
    Person p2 = new Person();
    p2.setId(3);
    p2.setAccount(444.5f);
    p2.setName("王五");
    list.add(p);
    list.add(p1);
    list.add(p2);
    Collections.sort(list,cp);
                                  
    for (Person pp : list) {
        System.out.println(pp.getId()+"--"+pp.getName()+"--"+pp.getAccount());
    }
}
                               
}


除了Comparator这接口,还有Comparable这个接口,我们可以自定义compare to方法

你可能感兴趣的:(list排序)