2015-07-19 22 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); 
} 
相关问题