这是我写的翻转一个数组的元素的顺序,大家有什么意见,哪里需要改正
package com.mingrisoft;
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.id) {
return 1;
} else if (id < o.id) {
return -1;
}
return 0;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("员工的编号:" + id + ", ");
sb.append("员工的姓名:" + name + ", ");
sb.append("员工的年龄:" + age);
return sb.toString();
}
}
这是我的测试类:
public class Test {
public static void main(String[] args) {
List<Employee> list=new ArrayList<Employee>();
list.add(new Employee(3,"Java",21));
list.add(new Employee(2,"Java",22));
list.add(new Employee(1,"Java",23));
System.out.println("排序前:");
for (Employee employee : list) {
System.out.println(employee);
}
System.out.println("排序后:");
Collections.sort(list); //执行自动排序
for (Employee employee : list) {
System.out.println(employee);
}
}
} |
|