简体   繁体   中英

Passing a string as a reference in Java?

I don't think i have the terminology correct, haven't been one for that. What i'm trying to do is get a string back , then use it to run functions. .. Example :

int slotNumber = ((j*3)+i+1);
String slotString = "slot"+slotNumber;

Regularly I can do this :

slot12.Draw();

And I want to be able to do this :

slotString.Draw();

With it substituting slotString with slot12 in a dynamic scenario. If i truly have to i could do something similar to :

if (slotString == slot1) slot1.Draw();
if (slotString == slot2) slot2.Draw();

And such, but i dont really want to use x number of lines for x number of slots.

Any help is appreciated :D

A possible solution would be to use a HashMap where the key is the slotNumber and the value points to the slot. Then you could do something like the following.

//Initialize at the start of your program
HashMap<int, Slot> SlotHash = new HashMap<int, Slot>();

//Code to retrieve slot and call Draw().
Slot select = SlotHash.get(slotNumber);
select.Draw();

Maybe use a Map if your slots are sparsely-packed. If they're densely-packed, you might be able to use an array of slots. In either case, you do the slot lookup based on index and then call Draw on the looked-up slot.

You would have something like this:

Slot slot1 = new Slot("slot1");
Slot slot2 = new Slot("slot2");
SlotController controller = new SlotController();
controller.add(slot1);controller.add(slot2);

String someSlotNumber = ".....";
controller.draw(someSlotNumber);

See the definition of the classes below:

class SlotController {
    Map<String, Slot> slotMap = new HashMap<String, Slot>();
    public void addSlot(Slot aSlot) {
        slotMap.put(aSlot.getSlotName(), aSlot);
    }

    public void draw(String slotName) {
        slotMap.get(slotName).draw();
    }


}

class Slot {
    private String slotName;
    public Slot(String name){
        slotName = name;
    }

    public String getSlotName() {
        return slotName;
    }

    public void draw() {

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM