首先,对象要实现Comparable接口,自然需要重写compareTo方法
在compareTo里定义哪个排前面,中间就是return 0
compareTo方法中要确定:
1.拿哪个属性比较
2.怎么样就可以排在前面
3.排在前面返回1,排在后面返回-1
public class Employee implements Comparable<Employee>{ private int id; private String name; private int age; public Employee(int id,String name,int age){ this.id = id; this.name = name; this.age = age; } @Override public int compareTo(Employee o) { if(id > o.getId()){ return 1; }else if(id < o.getId()){ return -1; } return 0; } /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the age */ public int getAge() { return age; } /** * @param age the age to set */ public void setAge(int age) { this.age = age; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("员工编号:"+getId()+","); sb.append("员工姓名:"+getName()+","); sb.append("员工年龄:"+getAge()); return sb.toString(); }
list内对象的排序:
1.声明list
2.添加元素
3.用Collections.sort(list);方法完成排序
public static void main(String[] args) { List<Employee> list = new ArrayList<Employee>(); list.add(new Employee(3,"王志",21)); list.add(new Employee(2,"李农",22)); list.add(new Employee(1,"郭楠",23)); //先遍历,在遍历中打印每个对象 System.out.println("排序前:"); for(Employee e : list){ System.out.println(e); } Collections.sort(list); System.out.println("排序后:"); for(Employee e : list){ System.out.println(e); } }
时间: 2024-10-31 19:08:11