Multi-valued Reversible enum in Java

Sometime back I proposed a reversible enum pattern in my post. One thing missing from that implementation was the ability to successfully lookup the enum constants in cases where enum constants can have multiple values. To accomplish this, I utilized another feature introduced in Java 5, namely varargs or variable argument support. This way while building the key for the map, we utilize all the values for a constant and use the varargs in the reverse() method of the enum.

Let’s look at the interface MultiValueReversibleEnum that denotes an enum as reversible and that an enum should implement.

The things to notice in this interface are:

  • getAllCode() method - It returns an array of all the possible values for an enum constant
  • reverse( E ... code ) method - You can see the usage of varargs here. You basically give all the possible values for the enum constant you want to lookup in the right order



Next we need to look at the map MultiValueReverseEnumMap that will store the enum constants and their value mappings.

As you can see, the getAllCodes() defined in the interface is used to build the key for the map. Also, the get( final K ... enumValues ) method that looks up the value in map uses varargs.



Now it’s time to glue everything together and see how to use the interface and map to build a multi-valued reversible enum. We will write a test class MultiValuedEnumTest.

If you run this class, you should see following getting printed:

Reverse for [1, 11]: ONE
Reverse for [2, 22]: TWO

It’s all very simple and straightforward. If you have any suggestions or feedback to improve this, please leave me a comment.

Share and Enjoy:
  • Digg
  • del.icio.us
  • description
  • Technorati
  • Reddit
  • Facebook
  • blogmarks
  • YahooMyWeb
  • Ma.gnolia

1 Comment »

  1. christian heinzer said,

    May 10, 2007 @ 4:44 pm

    Good work: exactly what I was looking for.

    One word of warning though: The buildKey method in MultiValueReverseEnumMap is dangerous: hashCode() doesn’t guarantee uniqueness - as an example try with single String values and use .reverse( “0-42L” ) and .reverse(”0-43-”): they will return the same enum.

RSS feed for comments on this post · TrackBack URI

Leave a Comment