【问题标题】:How to Get Index of an Item in a 2D Array Java如何在二维数组 Java 中获取项目的索引
【发布时间】:2015-10-07 02:44:38
【问题描述】:

我在尝试从 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,然后在创建时添加每个值)。

【问题讨论】:

  • 有一些方法可以"predefine" a map(即有一个很好的简短方法来定义它们)
  • 谢谢。不过,对于许多值来说,这有点乏味。
  • 地图绝对是这里正确的存储类型。随着数组的增长,您的数组查找将变得越来越慢。数组更容易写下来,但这不值得更糟糕的性能。

标签: java multidimensional-array indexing


【解决方案1】:

如果您希望代码可扩展并保持高性能,您可能想尝试使用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);
            }
        }
    }

【讨论】:

    【解决方案2】:

    这将完成工作....

    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
        }
    }
    

    【讨论】:

    • 谢谢。我希望避免使用循环,并认为可能有一些内置函数。
    • 为此,@wonderb0lt 建议您必须使用Collections,如Map
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 2020-06-30
    • 2013-05-02
    相关资源
    最近更新 更多