john tame
john tame

Reputation: 21

Overriding compareTo at Enums

I want to sort this Enum as reversed alphabetical order and return it. When I try to use compareTo method by overriding it I saw that it is declared as final.

Is there a way to override Enum similar with compareTo

How is it possible to sort this so I get:

D,C,B,A

public enum Test { 
 C(1)
 B(2)
 A(3)
 D(4)
}

Upvotes: 2

Views: 1371

Answers (2)

Sean Mickey
Sean Mickey

Reputation: 7716

The Enum implementation of compareTo() is based on the enum's ordinal value.

The ordinal is:

  • A primitive final int value
  • Assigned during construction
  • Based on the order of enum declaration
  • Starting at 0 (zero)

So, if you would like the enum to sort in a different order, you can simply declare them in that order:

public enum Test { D(4), C(1), B(2), A(3) }

(not sure what the values you pass to the constructor represent, so I maintained your values)

Upvotes: 1

Doi9t
Doi9t

Reputation: 111

Since you can't implement the java.lang.Comparable on enum, one way is to create a wrapper java.util.Set to compare the enum on the name.

Set<Test> testEnumSet = new TreeSet<>(new Comparator<Test>() {
   @Override
   public int compare(Test first, Test second) {
      return second.name().compareTo(first.name());
   }
});

testEnumSet.addAll(Arrays.asList(Test.values()));

This will produce the sort

[D, C, B, A]

To change the order to ascending:

return -(second.name().compareTo(first.name()));

Upvotes: 0

Related Questions