Women in Technology

Hear us Roar



Article:
  Enums in Java (One More Time)
Subject:   enum-as-objects as array-index
Date:   2003-04-24 13:04:36
From:   anonymous2
Since the presented enums-as-objects pattern as an .ord() method which returns a unique int for each, I dispute that the pattern doesn't solve any part of #4 (efficiency for arrays/swithces).


Example:


Day day = Day.THURSDAY;
int[] countOnThatDay = ...;
int countOnThursday = countOnThatDay[day.ord()];


For a switch, one could get the integer value out, but not use the .ord() of each constant as a case value.


So, enums-as-objects, it seems to me, could solve half of #4.

Main Topics Oldest First

Showing messages 1 through 1 of 1.

  • enum-as-objects as array-index
    2003-04-25 11:55:18  jimoore [View]

    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.