Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use enums for array indexes in Java

Tags:

java

enums

While reading Effective Java I came across the suggestion to "use enums instead of int constants". In a current project I am doing something similar to that below:

int COL_NAME = 0; int COL_SURNAME = 1;  table[COL_NAME] = "JONES"  

How would I use enums instead to achieve this? Due to the interface I'm forced to use, I must use an int for my index. The example above is just an example. I'm actually using an API that takes an int for index values.

like image 869
K2J Avatar asked Mar 24 '11 10:03

K2J


People also ask

Can enum be used in array index?

It is perfectly normal to use an enum for indexing into an array. You don't have to specify each enum value, they will increment automatically by 1. Letting the compiler pick the values reduces the possibility of mistyping and creating a bug, but it deprives you of seeing the values, which might be useful in debugging.

Can we have array of enum in Java?

Enum IterationThe static values() method of the java. lang. Enum class that all enums inherit gives you an array of enum values. Let us use the same enum type defined in the SimpleEnumExample class, , Days, and iterate through its values.

Can you index an enum?

Yes you can programmatically index an enum, text, or menu ring. An easy way to do this is to type cast the iteration terminal of a While or For Loop to the enum, text, or menu ring that you want to index.

Can an enum have an array?

Enums are value types (usually Int32). Like any integer value, you can access an array with their values. Enum values are ordered starting with zero, based on their textual order. MessageType We see the MessageType enum, which is a series of int values you can access with strongly-typed named constants.


1 Answers

Applying one usefull pattern together with an anti-pattern often fails ;-)

In your case using an array for not-really array-like data provides a problem when you want to replace int constants with enum values.

A clean(er) solution would be something like an EnumMap with the enum values as keys.

Alternatively you could use table[COL_NAME.ordinal()] if you absolutely must.

If some API forces you to pass around int values but you have control over the actual values (i.e. you could pass your own constants), then you could switch to using enum values in your code and convert to/from enum only at the places where your code interfaces with the API. The reverse operation of enumValue.ordinal() is EnumClass.values()[ordinal]).

like image 171
Joachim Sauer Avatar answered Oct 09 '22 13:10

Joachim Sauer