Enums in Java (One More Time)
Subject:   enum-as-objects as array-index
Date:   2003-04-25 11:55:18
From:   jimoore
Response to: enum-as-objects as array-index

I think that I am in partial agreement with your statements, but there is some confusion over the wording. Criterion #4 addressed efficiency only, and did not mention arrays and switches. Criterion 3 addressed language integration, and this is where I discussed arrays, switches, and language operators. In some sense your comments pertain to both criteria.

Relative to criterion #3 (language integration), it is true that the ord() method returns an int that can be used as an index into an array. Therefore if a is an array, then a[Day.THURSDAY.ord()] references the array item with index 4. Personally, I would prefer to use Day.THURSDAY (without the method call), but that is of relatively minor importance, and so the enums-as-objects pattern does support index into an array as you have stated. However, it still doesn't integrate well with other language features such as language operators and switch statements, so I wouldn't say that it solves "half" of this criterion.

Relative to criterion #4 (efficiency), the article states that the enums-as-objects pattern satisfies both criteria 1 and 4, but I would like to elaborate a little on that statement. Using the approach illustrated in the article, in order to get the integer value from the object one must call the ord() method. One approach that others have used is to make the ord instance variable public and eliminate the need for an ord() method. Since the instance variable is declared to be final, making it public does not violate the basic principles of encapsulation and information hiding. I ran a little unscientific benchmark testing this change, and although the overhead of a method call is not very large, eliminating it improved the performance by a factor of three in my benchmark. So even though I stated that criterion #4 was met by this approach, it is possible to improve efficiency even more.

1 to 1 of 1
  1. enum-as-objects as array-index
    2003-08-08 04:08:14  anonymous2 [View]

    • enum-as-objects as array-index
      2003-08-08 04:10:37  anonymous2 [View]

1 to 1 of 1