這兩個方法常常搞混淆,現對其進行總結以加深記憶。java
下面咱們寫一來看看上面兩個方法是怎麼用的:ide
首先,寫一個User類,代碼以下:函數
public class User implements Comparable<Object>{ int id; String name; public User(int id,String name){ this.id = id; this.name = name; } /* * Getters and Setters */ public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int compareTo(Object o) { if(this ==o){ return 0; } else if (o!=null && o instanceof User) { User u = (User) o; if(id<=u.id){ return -1; }else{ return 1; } }else{ return -1; } } }
接下來,咱們寫一個測試類Test:測試
public class Test{ //編寫Comparator,根據User的id對User進行排序 private static final Comparator<User> COMPARATOR = new Comparator<User>() { public int compare(User o1, User o2) { return o1.compareTo(o2);//運用User類的compareTo方法比較兩個對象 } }; public static void main(String[] args) { ArrayList<User> student = new ArrayList<User>(); User user1 = new User(1,"yueliming"); User user2 = new User(2,"yueliming"); Collections.sort(student, COMPARATOR);//用咱們寫好的Comparator對student進行排序 for(int i=0;i<student.size();i++){ System.out.println(student.get(i).getId()); } } }