我在尝试从 Java 中的 2D int 数组获取特定项目的索引时遇到问题。
这就是我所拥有的......
private int[][] mobPoints = {
{9300127,2},{9300128,2},{9300129,2},{9300130,3},{9300131,3},
{9300132,3},{9300133,3},{9300134,4},{9300135,4},{9300136,5}};
每个数组中的第一个数字是生物识别号,第二个数字是它所值的点数。我希望它的工作方式是,当玩家杀死一个生物时,服务器会检测到这一点,并通过一个方法发送它,该方法会增加一个变量,该变量的值是该生物所值的点数。示例:
public void addPoints(int mobid) {
}
我遇到的麻烦是使用给定的 mobid 并检索它的值(value)。我不想使用 HashMap 或 ArrayList,因为我似乎无法预定义它们(我必须创建一个新的 ArrayList,然后在创建时添加每个值)。
最佳答案
您可能想尝试使用 HashMap<Integer, Integer>
相反,如果您希望代码能够扩展并保持性能。
public class MobScene {
private HashMap<Integer, Integer> mobs = new HashMap<Integer, Integer>(10);
// Note that '10' is the initial capacity of the Collection.
// I only use it as I already know the given capacity and avoid extra memory being reserved.
public MobScene() {
mobs.put(9300127,2);
mobs.put(9300128,2);
mobs.put(9300129,2);
mobs.put(9300130,3);
mobs.put(9300131,3);
mobs.put(9300132,3);
mobs.put(9300133,4);
mobs.put(9300134,4);
mobs.put(9300135,5);
mobs.put(9300136,6);
}
public void addPoints(int mobid) {
if(mobs.contains(mobid)) {
mobs.put(mobs.get(mobid) + 1);
}
}
}
关于java - 如何获取 2D 数组 Java 中项目的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31474798/