Arraylist的对象排序

来源:互联网 发布:linux xwindows安装包 编辑:程序博客网 时间:2024/06/05 02:03
package test;import java.awt.List;import java.util.ArrayList;import java.util.Collection;import java.util.Collections;import java.util.Scanner;//write here//要实现comparable接口中的compareToclass Employee implements Comparable {    String str;    int id, age;    Employee(int id, String str, int age) {        this.id = id;        this.str = str;        this.age = age;    }    public int compareTo(Object o) {        Employee tgt = (Employee) o;        return (this.id < tgt.id ? -1 : (this.id == tgt.id ? 0 : 1));    }}public class Belle {    public static void main(String[] args) {        Scanner scan = new Scanner(System.in);        ArrayList<Employee> list = new ArrayList<Employee>();        for (int i = 0; i < 3; i++) {            int id = scan.nextInt();            String str = scan.next();            int age = scan.nextInt();            list.add(new Employee(id, str, age));        }        Collections.sort(list);        for (int i1 = 0; i1 < list.size(); i1++) {            Employee st = list.get(i1);            System.out.println("Id = " + st.id + ",Name = " + st.str+",Age = "+st.age);        }        // write here    }}
0 0
原创粉丝点击