سؤال

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?

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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.

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.

In my opinion, there are two solutions:

1) You can simulate 'C enum type' by class in Java:

class Animals {
    public static int DOG = 0;
    public static int CAT = 1;
    public static int MOUSE = 2;
}

In this case you manually set values to enum - in C it is automatically done by compiler.

Usage of enum looks like this

public class Test {
  public static void main(String[] args) {

    int[] age = new int[3];

    age[Animals.DOG] = 4;
    age[Animals.CAT] = 3;
    age[Animals.MOUSE] = 10;

    for (int i = 0; i < age.length; i++) {
        System.out.print(age[i] + " ");
    }
  }
}

I think this is bad solution because this break OOP principle of encapsulation (in class Animals).

2) You can use Java enum

enum Animals {
    DOG(0), CAT(1), MOUSE(2);
    int value;

    private Animals(int value) {
        this.value = value;
    }

    public int getValue() {
        return this.value;
    }
}

And example of usage

public class Test {
    public static void main(String[] args) {

        int[] age = new int[3];

        age[Animals.DOG.getValue()] = 4;
        age[Animals.CAT.getValue()] = 3;
        age[Animals.MOUSE.getValue()] = 10;

        for (int i = 0; i < age.length; i++) {
            System.out.print(age[i] + " ");
        }
    }
}

In Java enum is kind of class. For more details read this. There is no default values for enum and you have to set by yourself. In this example it is done with construcructor Animal(int value). Also, we cannot use Animals.DOG like integer values but we have to use method getValue().

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top