Monday, August 29, 2016

Reverse Lookup of Java Enum Values

I defined an enum with a structure similar to the following code:

public enum EnumWithIntValue {  
     ZERO(0),  
     ONE(1),  
     TWO(2),  
     THREE(3),  
     FOUR(4),  
     FIVE(5);

     private final int intValue;

     private EnumWithIntValue(final int intValue) {  
          this.intValue = intValue;  
     }

     public final int getValue() {  
          return this.intValue;  
     }  
}  

I then wanted to do a reverse lookup where I pass in a primitive int value and return the corresponding enum value. This was readily accomplished by adding the following static method to EnumWithIntValue:

public static final EnumWithIntValue valueOf(final int intValueParam) {
     for (EnumWithIntValue intValueEnum : values()) {
          if (intValueEnum.intValue == intValueParam) {
               return intValueEnum;
          }
     }

     throw new IllegalArgumentException("Invalid int value parameter " + intValueParam);
}

Hold up. What on Earth does values() do? If you look at the java.lang.Enum code from the JDK it does not exist. But according to the Enum Types section of the Java Tutorials:

The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type.

Ok all of that makes sense (sort of). However, what does values() do every time it is called? Or to put it another way, is values() giving me a reference to the same array each time it is called or is it cloning the encapsulated array and giving me a copy each time? Let's find out:

public static void main(final String[] args) {
     EnumWithIntValue[] array = values();

     System.out.println(array);

     array = values();

     System.out.println(array);
}

Well lookie here:

[Labc.test.EnumWithIntValue;@322ba3e4
[Labc.test.EnumWithIntValue;@4f14e777

Great, so each call to values() is obviously cloning the encapsulated array which is no good from a performance perspective. Of course the JDK is more worried about giving away the internal array reference which can lead to the possibility of someone altering said array which is also a big no-no. But for the purpose of my valueOf() method, that array is only used within my enum.

Therefore, let's cache the array inside the enum declaration and then update the valueOf() method to use the cached instance instead:

     // Declare the enum cache as a private constant
     private static final EnumWithIntValue[] enumValueArray = EnumWithIntValue.values();

     // Then update the values() call inside valueOf() to reference the enum cache instead
     for (EnumWithIntValue intValueEnum : enumValueArray) {
          ...
     }

And voila! A reverse enum lookup that performs as well as it looks!

14 comments:

  1. The blog gave me idea to reverse java enum values Thanks for sharing it
    Hadoop Training in Chennai

    ReplyDelete
  2. After reading this blog I am very strong in this topics and this blog is really helpful to all.. Explanation are very clear so it is easy to understand.. Thanks for sharing this blog…
    Big Data Analytics Training in Chennai | Web Designing Training in Chennai

    ReplyDelete
  3. You have provided a nice article, Thank you very much for this one. And I hope this will be useful for many people. And I am waiting for your next post keep on updating these kinds of knowledgeable things
    Java Training in Chennai
    Java Training in Coimbatore
    Java Training in Bangalore

    ReplyDelete
  4. Excellent blog thanks for sharing Looking for the best creative agency to fuel new brand ideas? Adhuntt Media is not just a digital marketing company in chennai. We specialize in revamping your brand identity to drive in best traffic that converts. Buckle up for a ride that is going to be filled with SEO, Social media marketing, unique Graphic & Logo design and efficient ads strike the perfect chord! Join the Adhuntt Media adventure right at Adhuntt Media.
    digital marketing company in chennai

    ReplyDelete
  5. Your topic is very nice and helpful to us … Thank you for the information you wrote.

    Learn Hadoop Training from the Industry Experts we bridge the gap between the need of the industry. Bangalore Training Academy provide the Best Hadoop Training in Bangalore with 100% Placement Assistance. Book a Free Demo Today.
    Big Data Analytics Training in Bangalore
    Tableau Training in Bangalore
    Data Science Training in Bangalore
    Workday Training in Bangalore

    ReplyDelete
  6. wonderful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article resolved my all queries. keep it up. leovely page
    Ai & Artificial Intelligence Course in Chennai
    PHP Training in Chennai
    Ethical Hacking Course in Chennai Blue Prism Training in Chennai
    UiPath Training in Chennai

    ReplyDelete
  7. This article provided me with a wealth of information. The article is incredibly helpful and offers some of the most useful information. Thank you for sharing it with us. web development company in chennai

    ReplyDelete
  8. Really, this is very important information which is shared by you. This info is meaningful and important for everyone to increase our knowledge about it. Always keep sharing this kind of info. Thank you. Read more info about gif construction

    ReplyDelete
  9. You wrote this post very carefully.Web Design in Tampa The amount of information is stunning and also a gainful article for us. Keep sharing this kind of articles, Thank you.

    ReplyDelete