Rwarfield Rwarfield - 3 years ago 64
Java Question

Having two different ways to access object

I need help with coming up with a way to access/insert data into an array, I've seen it in other languages but not sure if I can do it in Java.

I want to do this:

modList[1] = new Mod(1, 10);

for(int i = 0; i < modList.size; i++)
obj.addMod(modList[i].getModID, modList[i].getAmount);


modList
is an array of
Mod
class objects that store an int,
modid
, and int,
amount
, the loop would add each
Mod
in the
modList
to
obj
. I want to tie each
modid
to a variable like
MOD_EXAMPLE1
. I was thinking about doing something like this:

enum{
MOD_EXAMPLE1(1);
}


So that when it inserted the above example of
(1, 10)
it would insert
MOD_EXAMPLE1
instead of 1. Is this possible to tie a number to
MOD_EXAMPLE1
using enum like that, or do I just have to have a nest in
addMod
like this to do it:

if(modid = 1)
type = MOD_EXAMPLE1;
and so on...

Answer Source

What about using fields in your enum? I think this equivalent to the C++ thing you mentioned. It lets you associate an arbitrary value with each item in the enum:

public enum Mod{
    MOD_EXAMPLE1(1),
    MOD_EXAMPLE2(2);

    private final int id;
    private int amount = 0;

    Mod(int id) {
        this.id = id;
    }

    public static Mod createMod(int id){
        for(Mod mod : Mod.values())
            if(mod.id == id)
                return mod;
    }

    public int getId(){
        return id;
    }

    public updateAmount(int amount){
        this.amount += amount;
    }

    public int getAmount(){
        return amount;
    }
}

Then you could do things like:

void addMod(int modId, int amount){
    modList[1] = Mod.createMod(modId); //stored as an enum
    modList[1].updateAmount(amount); //increments amount for this mod
}

int getMod(){
    return modList[1].getId();
}

The Java Enum Tutorial shows all this and more, I strongly suggest reading that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download