0

I am using a TreeMap, where key is an enum and value is an integer.

     TreeMap<Ingredient, Integer> inv;

     public Inventory(){
        inv = new  TreeMap<Ingredient, Integer>();
        inv.put(Ingredient.COFFEE, 10);
        inv.put(Ingredient.DECAF_COFFEE, 10);
        // and so on
     }

The Ingredient class is defined as

public enum Ingredient {

COFFEE {
    public double getCost() {
        return 0.75;
    }

    @Override
    public String toString() {
        return "Coffee";
    }
},
DECAF_COFFEE {
    public double getCost() {
        return 0.75;
    }

    @Override
    public String toString() {
        return "Decaf Coffee";
    }
},

// and so on

However, when i iterate the treemap after adding all the ingredients, the enum keys are not printed in lexicographical order.

If instead of enum it was a class I would be implementing compareto, can i do something similar for enum?

Saad
  • 21
  • 1
  • 2
  • Related http://stackoverflow.com/questions/519788/why-is-compareto-on-an-enum-final-in-java – Steve Kuo Jan 20 '16 at 00:35
  • btw, enums can have fields and constructors and can implement interfaces - you would be better to have a field for cost and a single getCost method declared in the body of the class. – Bohemian Jan 20 '16 at 00:39
  • While it is correct that the `TreeMap` without a comparator uses the natural order of the enum rather than the lexicographical order of whatever property, I don’t get how you noticed. The natural order of the declared constants `Ingredient { COFFEE, DECAF_COFFEE }` matches exactly the lexicographical order as `'C' < 'D'`… – Holger Jan 20 '16 at 15:01

1 Answers1

6

Enum already implements Comparable. It uses the order the enum constants are defined in, but sadly you can't override the compareTo-method to achieve lexicographical ordering because its is defined as final.

But you can pass a custom Comparator to the TreeMap.

toKrause
  • 512
  • 1
  • 4
  • 13
  • I see, so this means, the order i define the enums is not defined in sorted order, that is why the traversal is using the manual order i defined. – Saad Jan 20 '16 at 00:10