【问题标题】:How to get and compare integer array from a list in a list? [duplicate]如何从列表中的列表中获取和比较整数数组? [复制]
【发布时间】:2021-05-22 03:19:02
【问题描述】:

我有一个程序,它使用 java.awt 机器人获取屏幕图片,然后循环遍历像素并将某些颜色分类为整数数组列表中的块。我有一个List<List<int[]>> blocks。第一个列表是所有块的列表,第二个列表是块中所有像素的列表,整数数组是 2 值,即像素的 x 和 y。我首先尝试使用 for 循环遍历所有带有 list.contain 的块来查找数组,但这总是返回 false。我现在正在尝试使用这样的循环来找到它们。

boolean continuer = false;
boolean found = false;
for (List<int[]> thisBlock : blocks) {
    int[] newInt = new int[2];
    newInt[0] = i;
    newInt[1] = j;
    for (int[] thisInt : thisBlock) {
        if (thisInt == newInt) {
            continuer = false;
            found = true;
            System.out.println("Found pixel in block");
            break;
        }
        if (found) {
            break;
        }
    }
    if (found) {
        break;
    }
}
if (!found) {
    continuer = true;
}

这也总是返回 false。任何帮助将不胜感激。

【问题讨论】:

  • 你不会像这样比较数组:thisInt == newInt。这将测试两个数组引用是否指向同一个数组。见stackoverflow.com/questions/14897366/…。 (但在这种情况下,我认为您根本不应该比较数组。您应该将数组内容与ij 进行比较。)
  • 你还有一个多余的测试。 continuer 逻辑在我看来奇怪
  • 作为一个元建议,我建议您阅读rubberduckdebugging.com ...并将这些想法应用到您调试自己的代码的方法中。
  • 我不明白你刚才说什么。但是您的代码中的主要问题是我的第一条评论。 1)这是按值比较数组的错误方法,2)您可能应该按值比较数组。

标签: java arraylist


【解决方案1】:

数组不能与 == 运算符进行比较。 Arrays Class 提供了一些方法来对数组执行操作。使用 Arrays.equals(thisInt,newInt) 而不是 thisInt == newInt

【讨论】:

  • 在这种情况下,OP 根本不应该比较数组。更好的解决方案是if (thisInt[0] == i &amp;&amp; thisInt[1] == j) {
猜你喜欢
  • 1970-01-01
  • 2020-05-18
  • 1970-01-01
  • 2020-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-23
  • 1970-01-01
相关资源
最近更新 更多