简体   繁体   中英

How do I get back a string value from a hashmap with enums?

I already have the following classes:

public enum Tile {
PT_Blue_1(1, 1, "Blue 1", "blue_1.jpg"),...;
//Constructor, getter and setter

A factoryClass with the following hashmap for all tiles:

public static HashMap<String, EnumSet<Tile>> getAllTiles() {
    HashMap<String, EnumSet<Tile>> htAllTiles = new HashMap<>();
    htAllTiles.put("Tiles", EnumSet.allOf(Tile.class));
    return htAllTiles;
}

I get {Tiles=[Blue 1]} back.

Now I want to convert it with an interface to an array to get back the imagename to add the images to a gameboard:

    public ITile[] getTilesToBoard() {
    ITile[] returnPath = Arrays.copyOf(this.hmTiles.values().toArray(), this.hmTiles.values().size(), ITile[].class);
    return returnPath;
}

Here I get now a java.lang.ArrayStoreException and I don't know why. Can anyone see where the fault is?

At the end I want to use it to put it into a gridpane:

    ImageView[][] iV = new ImageView[COL][ROW];

    for (ITile tiles : model.gameBoard.getTilesToBoard()) {
      for(int i=0; i<COL; i++){
        for(int j=0; j<ROW;j++){
        iV[i][j] = new ImageView(ImageLoader.getImage(tiles.getTile().getPath()));
              gridPane.add(iV[i][j], i, j);
        }
    }

Thanks for any advice!

It looks like you have an EnumSet as your value:

htAllTiles.put("Tiles", EnumSet.allOf(Tile.class));

And you are trying to assign the array EnumSet s to an array of ITiles .

ITile[] returnPath = Arrays.copyOf(this.hmTiles.values().toArray(), this.hmTiles.values().size(), ITile[].class);

Here hmTiles.values() is giving you collection EnumSets back and not a collection of your enum values.

You will have to interate over the EnumSet before you can add the values to the array. Try something like this:

public ITile[] getTilesToBoard() {
    ArrayList<ITiles> returnPath = new ArrayList<>();
    for (EnumSet<Tile> tiles : this.hmTiles.values()) {
        for (Tile tile : tiles) {
            returnPath.add(tile);
        }
    }
    return returnPath.toArray(new ITiles[returnPath.size()]);
}

PS: Also, note that collection.toArray() returns an Object[], to get a specific type of array you need to use collection.toArray(T[] a)

The problem seems to be that Tile does not implement ITile . Here is a simplified snippet that works:

interface ITile {}

public enum Tile implements ITile {
    one, two, three;
}

public static void main(String[] args) {
    EnumSet tiles = EnumSet.allOf(Tile.class);
    ITile[] iTiles = Arrays.copyOf(tiles.toArray(), 2, ITile[].class);
    System.out.println(iTiles[0]);
}

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