Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a replacement for Arrays with enums as indexes?

Tags:

java

c

enums

I used to use enums as indexes in C. (each enum something like an alias for an int value) Example:

typedef enum {DOG, CAT, MOUSE} ANIMALS;
int[3] age;
...
age[DOG] = 4;
age[CAT] = 3;
age[MOUSE] = 10;

With enums as indexes, I can always be sure that I am updating the right cell. Furthermore, I need the simplicity of arrays as well.

I would like to do the same in Java. But, I cant seem to find a simple replacement. Does anyone know a replacement that can be used the same way as Array+enum combo did in C?

like image 529
coffeenet Avatar asked Apr 23 '14 08:04

coffeenet


3 Answers

Yes there is a fairly simple one. Use HashMaps.

Map<CustomEnum, Object> hashMap = new HashMap<>();

//Basic usage
hashMap.put(CustomEnumID, ObjectValue);
ObjectValue obj = hashMap.get(CustumEnumID); //Returns the value from the above line
hashMap.containsValue(CustomEnumID); //Return true or false
like image 147
DonyorM Avatar answered Oct 21 '22 03:10

DonyorM


Enum is pretty much object in Java. So basically you go for HashMap is you would like to introduce Object-Object relations in your code.

like image 34
Denis Kulagin Avatar answered Oct 21 '22 05:10

Denis Kulagin


As was already said in other answers, using Map<YourEnum, V> is a good way to do what you want to do. However, Java, actually, has a EnumMap (it does implement regular Map interface) which is designed especially for use with enum type keys, and, as said in the documentation, it is likely to be faster than using HashMap.

like image 42
izstas Avatar answered Oct 21 '22 04:10

izstas