2012-11-23 77 views
0

我有這個類: 排序的ArrayList中的Java

public class Contact { 
private String firstname; 
private String lastname; 
private List<Integer> phoneNumber; 
private Scanner in; 
public Contact(){ 
    phoneNumber = new ArrayList<>(); 
    firstname = lastname = ""; 
    in = new Scanner(System.in); 
} 
public void setFirstName(){ 
    firstname = in.nextLine(); 
} 
public void setLastName(){ 
    lastname = in.nextLine(); 
} 
public void setPhoneNumber(){ 
    phoneNumber.add(in.nextInt()); 
} 
public String getFirstName(){ 
    return firstname; 
} 
public String getLastName(){ 
    return lastname; 
} 
public Integer getPhoneNumber(int position){ 
    return phoneNumber.get(position); 
} 
} 

現在我想打一個類電話簿其中有我的聯繫..我想用

Arraylist<Contact> 

做它,因爲它贏得了沒有固定的大小。當我想按姓氏對這個數組列表進行排序時,我該怎麼辦?

+0

這個問題已經被問過無數次之前,並且可以很容易地看着在互聯網上。 http://stackoverflow.com/questions/9679769/sort-an-arraylist-of-objects –

回答

5

您的聯繫人類需要實現Comparable接口...然後您可以使用Collections.sort(list)對列表進行排序。

編輯: 如果你想有多種排序方式,那麼你也可以創建一個實現Comparator接口的類。您可以創建多個比較器(或使一個可配置的),那麼你可以通過比較器作爲第二個參數Collections.sort

這裏是一個鏈接解釋比較的解決方案:http://www.vogella.com/blog/2009/08/04/collections-sort-java/

+0

我不能讓類MyComparable實現比較器。你可以幫我嗎?我如何比較聯繫人的姓氏2並返回正確的?之後:Collections.sort(contacts,new MyComparable()); ? – Bbabis

+0

讓您的MyComparable類實現比較器而不是比較器,因爲您要比較聯繫人項目... – Tom

2

,你將不得不把在關於姓氏的自定義比較,無論是作爲一個單獨的類或匿名類:

OK,我編輯,因爲我有一些空閒時間,我想你是學習Java :)

這兩種方法添加到聯繫人類別測試:

public void setLastName(String lastname) { 
    this.lastname = lastname; 
} 
@Override 
public String toString() { 
    return getLastName(); 
} 

測試:

public class Sort { 

    static List<Contact> list = new ArrayList<Contact>(); 
    static Contact one = new Contact(); 
    static Contact two = new Contact(); 
    static Contact three = new Contact(); 
    public static void main(String[] args) { 
     one.setLastName("Smith"); 
     two.setLastName("Monks"); 
     three.setLastName("Aaron"); 
     list.add(one); list.add(two); list.add(three); 
     System.out.println("Before: " + list); 
     Collections.sort(list, new Comparator<Contact>() { 
      public int compare(Contact contact, Contact another) { 
       return contact.getLastName().compareToIgnoreCase(another.getLastName()); 
      } 
     }); 
     System.out.println("After: " + list); 
    } 
} 

你的結果應該是:

Before: [Smith, Monks, Aaron] 
After: [Aaron, Monks, Smith] 
+0

我想排序我的ArrayList contacts = new ArrayList <>(); (聯繫人是一個有很多領域的類)由聯繫人的字段lastname(字符串)..所以我會寫:Collections.sort(聯繫人,新比較器)..請幫我代碼..我遇到這個問題很多次我想要一個解決方案.. – Bbabis