2

I have a Person class with a constructor as such

Person(String name, String position, int birthYear)
{
    this.name = name;
    this.position = position;
    this.birthYear = birthYear;
}

I also have a Work class that has an ArrayList<Person> personnel that I need to sort recursively by birthYear. I am at a complete and total loss as to how to do this. The solution I need, by the assignment, cannot include interfaces. I know how to sort integer arrays, but I'm not sure how when there is an ArrayList of objects involved.

3
  • Implement Comparator or Comparable interface. check mkyong.com/java/…. Commented Jul 15, 2014 at 3:30
  • @ReiHinoX: The title of your question refers to sorting your objects recursively. What do you mean by that? Do you mean you need to use a recursive sort algorithm (e.g. Quicksort)? Commented Jul 15, 2014 at 3:35
  • @DanielPryden that's correct Commented Jul 15, 2014 at 18:32

5 Answers 5

3

Make sure your class Person implements Comparable. By doing that you have to implement the method:

int compareTo(Person o)

when you implement it you compare this.birthYear with o.birthYear and return 1,0 or -1 depends if the first is bigger than, equals or less than the latter.

After you've finished doing that, you can use Collections.sort(people) to sort the collection by birthYear.

You can also sort a collection of Person using a comparator:

List<Person> people = new ArrayList<Person>();
// add a few "Person"s to the list...
Collections.sort(people, new Comparator<Person>() {
      public int compare(Person a1, Person a2) {
        return a1.getBirthYear() - a2.getBirthYear();
      }
    }); 
Sign up to request clarification or add additional context in comments.

3 Comments

Isn't that ruled out by the requirement to not implement an interface?
@DanielPryden it is indeed ruled out.
@ReiHinoX in that case you can use the other option I showed (using a comparator).
0

I assume that "cannot include interfaces" means that Person is not allowed to implement any interfaces, not that you cannot use interfaces at all (which sounds like an absurd requirement).

The most straightforward solution is the one you've ruled out: you could make Person implement Comparable<Person> to define the "natural" sort order of Person instances. You can then pass your ArrayList to Collections.sort() and sort it.

However, that obviously doesn't work if you want to be able to sort Person instances more than one way, or if Person is a class you don't control (e.g. you aren't allowed to modify it to add an interface). In that case, you can use the overload of Collections.sort() that takes a Comparator. You will need to define a class that implements Comparator<Person> and pass an instance of that class into Collections.sort().

2 Comments

Like yourself, I'm not sure if "cannot include interfaces" means not being able to implement interfaces, but if that's the assumption, implementing Comparator<Person> is also implementing an interface ;)
It's for a class. My teacher literally said "Of course it's an absurd requirement. You have to learn this stuff so then you can go and tell other people that it's an absurd requirement when they ask."
0

First, if you have trouble with arraylists, the following Java Documentation might be helpful.

http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

So you have an arraylist of Person objects, named personnel. Use the .get(int index) to access each person object. For each person object in personnel, .birthYear gives you access to the birthYear you are looking for.

More specifically, how do you sort them? You can normally use the sort method from the collections class. Check the Documentation here:

http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html

If you want to write your own sorting algorithm (since you cannot include interfaces), instead of using one provided you can try the commonly recursive and nlogn time quicksort and mergesort. The steps are elaborated here:

http://en.wikipedia.org/wiki/Sorting_algorithm

Comments

0

Example of an ascending recursive sort for objects that contain an integer that does not use java built in features to do the heavy lifting for you :

    List<Person> recursiveSort(List<Person> personnel) {

    boolean changed = false;
    for (int i=0; i<personnel.size()-1; i++) { // Do not use for each format in recursive methods
        if (compare(personnel.get(i),personnel.get(i+1))>0) {
            changed = true;
            swap(personnel,i,i+1);
        }
    }

    if (changed) return sort(personnel); // Recursive call
    else return personnel;
}

int compare(Person p1, Person p2) {
    if (p1.birthYear < p2.birthYear) return -1;
    if (p2.birthYear < p1.birthYear) return 1;
    return 0;
}

void swap(List<Person> personnel, idx1, idx2) {
    try {
        Person swp = personnel.get(idx1);
        personnel.set(idx1, personnel.get(idx2));
        personnel.set(idx2, swp);
    catch (Exception e) {
        // Print warning
    }
}

I know how to sort integer arrays, but I'm not sure how when there is an ArrayList of objects involved.

Sorting an array of objects on a member integer attribute should be the exact same algorithm as sorting an array of integres, except that you need to access the integer attribute value. An example of this is :

        Collections.sort(personnel,new Comparator() {

        @Override
        public int compare(Person p1, Person p2) {
            if (p1.birthYear < p2.birthYear) return -1;
            if (p2.birthYear < p1.birthYear) return 1;
            return 0;
        }

    });

Comments

0

You can use

Collections.sort(List<T> list, Comparator<? super T> c) 

It can sort any list of type T, but you need to pass a comparator for ordering your elements.

You can alternatively use

Collections.sort(List<T> list) 

But this assumes that the elements of your list are Comparable. i.e. the elements implement Comparable interface. For this method to work you should correctly implement compareTo method of Comparable interface.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.