【问题标题】:sorting ArrayList of objects on 3 int fields在 3 个 int 字段上对对象的 ArrayList 进行排序
【发布时间】:2015-07-19 21:33:16
【问题描述】:

我下面的代码无法根据第一次收入、年龄和 postCode 对 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)

【问题讨论】:

    标签: android sorting arraylist


    【解决方案1】:
    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 );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-03
      • 2019-07-26
      • 2014-09-05
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      • 1970-01-01
      相关资源
      最近更新 更多