如何在2D数组中获取一个项目的索引



我在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和检索它的价值。我不想使用hashmap或ArrayLists,因为我似乎无法预定义它们(我必须创建一个新的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);
            }
        }
    }

这将完成工作....

public void addPoints(int mobid) {
    // create a boolean to know if key has been found
    boolean found = false;
    // iterate over first column of your matrix array
    for (int c = 0; c < mobPoints.length; c++) {
        // if the key still not found and is equal first column value 
        if (!found && mobPoints[c][0] == mobid) {
            // add points or do your stuff
            System.err.println("Value = " + mobPoints[c][1]);
            // mark as found
            found = true;
        }
    }
    if (!found) {
        // not found error
    }
}

相关内容

  • 没有找到相关文章