2015-07-19 2 views
0

Мой код ниже не сортирует ArrayList на основе первого дохода, затем возраста, затем postCode. Я читал много примеров в Интернете, но не смог найти рабочее решение. Пожалуйста помоги.сортировка ArrayList объектов на 3 int fields

Если список 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); 
} 
Смежные вопросы