Java 字典<字符串,列表<对象>>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12902733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:43:04  来源:igfitidea点击:

Java dictionary<String, List<Object>>

javadictionary

提问by Julius

I was making a game with XNA game studio and now I want to rewrite it in Java. It's something like a 2D Minecraft clone. For collision detection, I have to loop through all blocks in the game to check on whether the player is colliding with a block. With a huge number of blocks, it is impossible to do so, so I made a grid system. I divided the world into grids which contain blocks, and put them into a dictionary.

我正在使用 XNA 游戏工作室制作游戏,现在我想用 Java 重写它。这有点像 2D Minecraft 克隆版。对于碰撞检测,我必须遍历游戏中的所有块以检查玩家是否与块发生碰撞。有大量的块,这是不可能的,所以我做了一个网格系统。我将世界划分为包含块的网格,并将它们放入字典中。

Dictionary<string, List<Block>> gameBlocks;

Now I have only to loop through the blocks in the current grid.

现在我只需要遍历当前网格中的块。

This is the method to register a block:

这是注册块的方法:

public void RegisterBlock(Block block)
{
    idX = (int)(block.blockPosition.X / width);
    idY = (int)(block.blockPosition.Y / height);
    string id = idX.ToString() + "_" + idY.ToString();
    if (gameBlocks.ContainsKey(id))
    {
        gameBlocks[id].Add(block);
    }
    else
    {
        gameBlocks.Add(id, new List<Block>());
        gameBlocks[id].Add(block);
    }
}

Now I am trying to rewrite it in Java but I don't know how to put something into a Dictionary.

现在我正在尝试用 Java 重写它,但我不知道如何将某些内容放入字典中。

回答by Brian

Use Java's Mapinterface and HashMapclass. Your method would look like this in Java:

使用 Java 的Map接口和HashMap类。您的方法在 Java 中如下所示:

private Map<String, List<Block>> gameBlocks = new HashMap<String, List<Block>>(); // Java 6
// OR:
private Map<String, List<Block>> gameBlocks = new HashMap<>(); // Java 7

public void registerBlock(Block block) {
    idX = (int)(block.blockPosition.X / width);
    idY = (int)(block.blockPosition.Y / height);
    String id = idX + "_" + idY;
    if (gameBlocks.containsKey(id)) {
        gameBlocks.get(id).add(block);
    } else {
        gameBlocks.put(id, new ArrayList<Block>());
        gameBlocks.get(id).add(block);
    }
}

Notice some of the corrections I've made for Java's recommended formatting/naming styles.

请注意我对 Java 推荐的格式/命名样式所做的一些更正。

回答by kosa

Java has something called HashMapwhich may be useful for you. Here is documentation for HashMap.

Java 有一个叫做的东西HashMap,它可能对你有用。这是HashMap 的文档。

Example:

例子:

HashMap<string, List<Block>>