Armando Moncada
Armando Moncada

Reputation: 545

Need explanation of natural ordering in Java

Would you give an example of "choose the natural ordering inside the class."

I read Object Ordering in docs.oracle but it doesn't say how the natural ordering is decided in the case where there are multiple elements. If a class has elements such as name, age, address, phone number; which one gets picked to do the natural ordering?

Then, I read in a post here that one can decide the natural ordering. I am a Java newbie trying to tackle a homework assignment and taking my first stab at the collections framework.

Upvotes: 1

Views: 168

Answers (2)

James Cronen
James Cronen

Reputation: 5763

I prefer Comparator classes for this, even though the implementation looks a bit more heavyweight. The reason is that, for some objects, it's not always clear what's being compared. Using .compareTo() (that is, implementing IComparable) doesn't make it as clear as an explicit Comparator does.

BasketballPlayer player1 = new BasketballPlayer("Smith", 2.02);
BasketballPlayer player2 = new BasketballPlayer("Jones", 1.95);

List<BasketballPlayer> playersByHeight = new ArrayList<BasketballPlayer>();
List<BasketballPlayer> playersByName = new ArrayList<BasketballPlayer>();
playersByHeight.add(player1);
playersByHeight.add(player2);
playersByName.add(player1);
playersByName.add(player2);

Collections.sort(playersByName, new Comparator<BasketballPlayer>() {
    @Override
    public int compare(BasketballPlayer o1, BasketballPlayer o2) {
        return o1.getName().compareTo(o2.getName());
    }
});
Collections.sort(playersByHeight, new Comparator<BasketballPlayer>() {
    @Override
    public int compare(BasketballPlayer o1, BasketballPlayer o2) {
        return o1.getHeight().compareTo(o2.getHeight());
    }
});

Here I use an anonymous class, but you could make the Comparators their own (named) class if you like.

Upvotes: 1

jrad
jrad

Reputation: 3190

Yes, you are right in saying that one can decide the natural ordering. You'd be implementing Comparable and writing your own implementation of the compareTo() method. In that method, you decide what trumps what.

Upvotes: 2

Related Questions