Java: using an enumeration as an array reference

I would like to refer to an array with an enum type. This is a pretty standard thing in C ++ (my origin), however I'm not sure if this is possible / desirable in Java.

For example, I would like to have an enumeration, for example:

public enum Resource {
    COAL,
    IRON
}

Then I would like to refer like this:

Amount[COAL] // The amount of coal
Price[IRON]  // The price of iron

I do not want to create fields Amountand Price Resource, since I need a list of objects (orders for resources), grouped by resource type. Manually assigning int to each type is Resourceno better than public static int final BLAH, I feel, nothing worked.

In essence, I'm looking for a C ++ enumeration that tags things. I understand that this may be the β€œwrong” way of doing things in Java, so feel free to point me in the direction of the right Java ethos.

+5
6

++ . Java "" , .

, enum - ! EnumMap<Resource, Double>?

EnumMap , () . , , , Map - .

+12

. ++, enum int, Java enum . . ordinal(), int,

amount[COAL.ordinal()]
price[IRON.ordinal()]

. , :

IRON.price(amounts)
COAL.amount(prices)

, .

+1

Java , . , .

COAL.ordinal()

, , . , , . , .

.

Map<Resource, Order> orders = new HashMap<Resource, Order>();
orders.put(Resource.COAL, new Order(price, amount));
+1
0

. , , / . , , .

, Java 6. ! .

public enum Resource{
    COAL(0), IRON(1);
    int index;
    private Resource(int index){
        this.index=index;
    }
}
...
amount[Resource.COAL.index]=...

:

public enum Resource{
    COAL(538,0.5f), IRON(115,1.5f);
    int amount;
    float price;
    private Resource(int amount, float price ){
        this.amount=amount;
        this.price=price;
    }
}
...
Resource.COAL.amount=...

.

:

for(Resource resourceType: Resource.values()) { 
   String toOutput=resourceType.name()+" amount="+ resourceType.amount;
}
0

, :

Amount[COAL.ordinal()] // The amount of coal
Price[IRON.ordinal()]  // The price of iron

If you don't like this, constants may be your only option, i.e.

public class Resource {
    public static final int COAL = 0;
    public static final int IRON = 1;

}

Hope this helps.

-1
source

All Articles