当前位置: 代码迷 >> java >> 如何在2D数组Java中获取项目的索引
  详细解决方案

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

热度:40   发布时间:2023-07-31 11:05:01.0

我在尝试从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并获取它的价值。 我不想使用HashMaps或ArrayLists,因为我似乎无法预定义它们(我必须创建一个新的ArrayList,然后在创建时添加每个值)。

如果您希望代码能够缩放并保持高性能HashMap<Integer, Integer>可能要尝试使用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
    }
}
  相关解决方案