0

I am studying for a final, and im looking at a question from my midterm that i got wrong and honestly wasnt sure how to go about doing so. The question is as follows:

Rewrite the Person class so that if you have an ArrayList of Person objects, ArrayList, you can sort it using the Collections sort method. The sort method should sort the list first by decreasing age and then alphabetically (for people the same age).

The same code (Person class) that was provided in the question is below.

public class Person {
   public String name;
   public int age;
}

This was a midterm question so I had to hand write the code. I am wondering what is the efficient and proper way to answer this question. All answers or input is greatly appreciated. Thanks.

choloboy7
  • 287
  • 2
  • 7
  • 19

2 Answers2

2

I'd like to note @Kevin Bowersox answer that his answer sorts by ascending age and doesn't taken into account the second sort on name. Replace the compareTo with this to solve those two issues

@Override
public int compareTo(Person person)
{
    int ageSort = new Integer(person.age).compareTo(this.age);

    // If the ages aren't the same
    if(ageSort != 0)
    {
        return ageSort;
    }

    // otherwise sort on name alphabetically
    return name.compareTo(person.name);
}
Erich
  • 2,743
  • 1
  • 24
  • 28
1

Make the Person class implement the Comparable interface and provide an implementation for the CompareTo method.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Person implements Comparable<Person> {
    public String name;
    public int age;

    @Override
    public int compareTo(Person person) {
        return new Integer(this.age).compareTo(person.age);
    }


    public static void main(String[] args) {
        Person person = new Person();
        person.name = "Kevin";
        person.age = 28;
        Person person2 = new Person();
        person2.name="Bob";
        person2.age = 40;
        Person person3 = new Person();
        person3.name="Joe";
        person3.age = 90;

        List<Person> people = new ArrayList<Person>();
        people.add(person2);
        people.add(person3);
        people.add(person);

        Collections.sort((List<Person>)people);

        for(Person p:people){
            System.out.println(p.name);
        }
    }

}
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189