我正在开发一款使用多个 HashMap<Point, Integer>
的游戏存储分配给坐标的值。为了使其更简单并减少重复,我用一个自己的类扩展了 Point 类,称为 GamePoint。它有一个 equals() 方法,仅比较 x 和 y,该方法也适用于 Point。由于我不再需要 HashMap 中的键值关系,因此我只需将其放入 ArrayList 中即可。
使用 HashMap 我有这个:
HashMap<Point, Tile> tileMap; //already built at that stage
public static Tile getTile(int x, int y) {
Point p = new Point(x,y);
if(matrix.containsKey(p)){
return tileMap.get(p);
} else return Tile.BOUNDS;
}
从该图 block (这是一个枚举)中,我可以获得图像索引。 现在我这样做是为了从 ArrayList 中获取我的值:
ArrayList<GameTile> gameTiles; //already built at that stage
public static int getGameTileIndex(int x, int y) {
Point p = new Point(x,y); //only for finding the coordinates
for(GameTile gt : gameTiles){
if (p.equals(gt)){
return gt.getImageIndex();
}
}
return 0; //empty tile
}
不幸的是,没有可以返回 GameTile 的直接方法。迭代真的非常非常慢,因为我有 1,000,000 个条目,最终游戏中还会有更多。
这是我需要知道的:
迭代 ArrayList 是检索 GameTile 的正确方法吗?我应该继续使用 HashMap 并使用类似 HashMap<Point, GameTile>
的东西吗? ?
或者我可以以某种方式使用 get(int index) 方法,知道数组中充满了类似于此的嵌套循环:
List<Point> referencePoints;
for (int x; x<width; x++){
for (int y; y<height; y++){
Point p = new Point(x,y);
height = calculateHeight(x,y);
tileMap.put(p, height);
referencePoints.add(p);
}
}
for (Point p: referencePoints){
GameTile tile;
if (float height = getHeight(p) > THRESHOLD){
tile= new GameTile.GrassTile(p.x,p.y);
}
else {
tile= new GameTile.WaterTile(p.x,p.y);
}
gameTiles.add(tile);
}
注意:我确实觉得有一种非常合乎逻辑的方法可以使用 x,y 变量进行索引检索,但我现在无法集中精力。
编辑: 我选择了 HashMap,它现在很有魅力。这些答案虽然给了我新的视角,但无法帮助我解决问题,而且仍然如此。我找到了一种适合我的情况的解决方法,并且现在将使用它。
最佳答案
Is iterating the ArrayList the right way for retrieving the GameTile?
没办法。您的 HashMap
实现远远优于迭代。
Should I stay with the HashMap and use something like HashMap ?
没有。对 ArrayList
进行索引将比使用 HashMap
快得多。
Or could I somehow use the get(int index) method?
是的。老实说,如果您使用二维数组(x x y),可能会更容易理解。但它会按照你在伪代码中布置的方式工作。这将是您最有效的解决方案。
关于java - 从 ArrayList 获取坐标(x,y)的快速方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28333807/