user468311
user468311

Reputation:

Java comparing custom objects

I've got ArrayList of custom objects. I need to implement sorting by different parametres, i.e. year and price both ascending and descending. What's the best way to do it? I thought about implementing Comparator and passing sort mode to constructor during instantiation of comparator. Is that good idea?

Upvotes: 1

Views: 14003

Answers (5)

Jeremy
Jeremy

Reputation: 22425

Yes. A custom Comparator is a really good way to do it.

As mentioned by @Tom and @Puce, you can reverse the order of your Comparator on the fly.

Upvotes: 2

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

I would suggest using a different Comparator implementation per sort type. Anonymous inner classes, enums and, in Java SE 8(!), lambdas, are good ways to implement Comparator and other stateless function-like objects.

You can reverse with Collections.reverseOrder.

Upvotes: 2

corsiKa
corsiKa

Reputation: 82579

That's one way. But, it really only makes sense if it's a default way. Consider the following Customer class. Typically, you always sort customers by name. But sometimes, you want to sort them by their credit limit.

It makes sense to implement Comparable for convenience. At the very least, you can make the comparators public final components of the class so users have easy access to them, and you can trust they were written by the author of the class (or at least someone with familiar working knowledge of the class.)

class Customer implements Comparable<Customer> {

    public final Comparator<Customer> byCreditLimit = new Comparator<Customer>() {
        public int compare(Customer c1, Customer c2) {
            return c1.creditLimit.compareTo(c2.creditLimit);
        }
        public boolean equals(Object o) {
            return o == this;
        }
    }

    private String name;
    private BigDecimal creditLimit;

    public Customer(String name, BigDecimal creditLimit) {
        this.name = name;
        this.creditLimit = creditLimit;
    }

    public boolean equals(Object o) {
        if(o instanceof Customer) {
            Customer c = Customer(o);
            return name.equals(c.name);
        }
        return false;
    }

    public int hashCode() {
        return name.hashCode();
    }

    public int compareTo(Customer c) {
        return name.compareTo(c.name);
    }
}

Upvotes: 2

CPerkins
CPerkins

Reputation: 9018

The canonical answer is to implement two Comparators - one which sorts in ascending order, and one in descending.

Upvotes: 0

Related Questions