Laura
Laura

Reputation: 103

Sort ArrayList using Comparable

I'm working on a project where I need to be able to sort an ArrayList of Car objects by price. In my Car class, I have

public class Car implements Comparable

and in the body of the code is the compareTo method:

    public int compareTo(Object o)
    {
        Car rhs = (Car)o;

        if (price > rhs.price)
            return 1;
        else if (price < rhs.price)
            return -1;
        else
            return 0;
    }

I just don't understand how to implement this method to sort by price- what does carList need to be compared to? I know this isn't correct but so far this is the sorting method.

public void sortByPrice()
{
    Collections.sort(carList.compareTo(o));
}

Upvotes: 1

Views: 9497

Answers (4)

buddy123
buddy123

Reputation: 6297

You're almost done! Only call to Collections.sort(carList); and that will by itself, use the overridden compareTo. Actually, when you're not implementing compareTo, you'll have the very basic implementation, and calling Collections.sort(..) will use the basic implementation, which is comparing pointers in that case.

Upvotes: 0

Makoto
Makoto

Reputation: 106389

Two problems: one syntatical and one conceptual.

The first issue is that while your compareTo is technically correct, you want to type-bind it to Car instead of Object.

public class Car implements Comparable<Car>

Inside of your compareTo method you'd then substitute Object for Car. You would also want to check for null.

The second is that sortByPrice sounds specific, but since compareTo is comparing based on price, that's somewhat okay.

All you'd need to do is call Collections.sort on the actual collection:

Collections.sort(carList);

Upvotes: 4

Giovanni Botta
Giovanni Botta

Reputation: 9816

Your Car class must implement Comparable<Car>. Then your compareTo method will have signature:

public int compareTo(Car other) {}

As per the documentation, this method should:

Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

Then given a List<Car>, say list, you can call Collections.sort(list).

Upvotes: 0

Smutje
Smutje

Reputation: 18123

Normally, one sorts a collection using

Collections.sort(collection)

while collection has to implement Comparable and sort uses the compareTo method to sort collection.

Upvotes: 0

Related Questions