2015-07-19 59 views
0

我的代碼下面未能根據第一個收入排序ArrayList,然後是age,然後是postCode。 我在網上閱讀了很多例子,但沒有提出一個可行的解決方案。請幫忙。排序3個int字段上的對象的ArrayList

如果一個4人列表中包含int數據,並通過一個數字進行簡化,如下所示。

  • 1,2,3
  • 0,0,0
  • 1,3,4
  • 1,3,2

    那麼就應該對它們進行排序是

  • 0,0,0

  • 1,2,3
  • 1,3, 2
  • 1,3,4

謝謝

public class Person implements Comparable<Person> { 
private int income; 
private int age; 
private int postCode; 

public Person(){} 
public Person(int income, int age, int postCode) { 
    this.income = income; 
    this.age = age; 
    this.postCode = postCode; 
} 

@Override 
public int hashCode() { 
    int result = income; 
    result = 31 * result + age; 
    result = 31 * result + postCode; 
    return result; 
} 

@Override 
public int compareTo(Person another) { 
    return ((Integer) income).compareTo(another.getArea()); 
} 

}

Collections.sort(myList中)

回答

0
public int compareTo(Person another) 
{ 
    if (this.income == another.income) 
    { 
     if (this.age == another.age) 
     { 
      return ((Integer) this.postCode).compareTo(another.postCode); 
     } 

     return ((Integer) this.age).compareTo(another.age); 

    } 

    return ((Integer) this.income).compareTo(another.income); 
}