Dominicus1165
Dominicus1165

Reputation: 11

Refere to an element of an array

I have this code and I want to call a specific element of an array:

public class Game{
    ...
    public final Equipment[] equipment= {new Suit(this), new Sword(this), new Shield(this)};
    ...
}

Usually you call it like this game.equipment[0] but I want to call it like this game.equipment[Suit].

I don't want to use getters like

public Equipment getSuit() {return equipment[0];}

Couldn't find anything via Google.

My idea was

public final Equipment suit = equipment[0];

but then I have to use game.suit and I don't want that.

EDIT: Thank you for your answers and help. My solution:

    public final Enhancement[] enhancements = {new Suit(this), new Sword(this), new Shield(this)};
    public static final int Suit = 0;
    public static final int Sword = 1;
    public static final int Shield = 2;

In other classes I refer with this:

import static pp.frame.model.worlds.GameWorld.Suit;

world.equipment[Suit].apply();

I know that this is NOT beautiful but it gets the job done and my prof only wanted it to look like this.

Upvotes: 0

Views: 58

Answers (2)

Nicolas
Nicolas

Reputation: 8650

You would need a Map to do that. It is basically a key-value array (or dictionary) that allows you to get values by their key. It takes two generic parameter. One for the key and one for the values.

You can use it as such.

Map<String, Equipment> equipment = new HashMap<>();
equipement.put("suit", new Suit(this));
equipement.put("sword", new Sword(this));
equipement.put("shield", new Shield(this));

You can then use the get method to retrieve it's value.

Equipment suit = equipment.get("suit");

Please note here that we are using an HashMap but there is many type of Map you can use. HashMap is simply the more common one.

Also, I'm using the anonymous initializer syntax, which might not be the best choice for performance. Frontear, and I, suggest looking into this post for more information on the subject.

Upvotes: 1

Sharon Ben Asher
Sharon Ben Asher

Reputation: 14328

if you insist on keeping the equipment in an array, you can search the array for a suit according to the concrete type:

Suit suit = (Suit)
    Arrays.stream(equipment)
        .filter(equipmentItem -> equipmentItem instanceof Suit)
        .findFirst()
        .orElse(null);

note that if there is no Suit in the array, a null reference is returned. Also, if there are two Suits, the first is returned.

Upvotes: 1

Related Questions