tokhi
tokhi

Reputation: 21616

Java - modify compareTo method to sort integers from 1

I'm trying to sort an ArrayList of objects using of comparable interface:

public class Unit implements Comparable<Unit>{
    // attributes
    int position;
    @Override
    public int compareTo(Unit other) {
        return Integer.compare(position, other.position);
    }
}

Now I sort the ArrayList using:

List<Unit> units = getAllUnits();
Collections.sort(units);

The above will sort all the units starts from position 0 but I want this to start from position 1 because the default value of position is zero.

How can I modify the compareTo method?

Upvotes: 2

Views: 1081

Answers (1)

jlordo
jlordo

Reputation: 37823

(Using the information in your comment, that there will be no negative numbers,) you should be able to use this:

public int compareTo(Unit other) {
    if (position != other.position) {
        if (position == 0) {
            return 1;
        } else if (other.position == 0) {
            return -1;
        }
        return Integer.compare(position, other.position);
    } else {
        return 0;
    }
}

Update: It will also work for negative numbers, example output: [-1, 1, 2, 0, 0]

Upvotes: 3

Related Questions