'包含'方法不适用于ArrayList& lt [int []>>,还有另一种方法吗? [英] The 'contains' method does not work for ArrayList<int[]>, is there another way?

查看:63
本文介绍了'包含'方法不适用于ArrayList& lt [int []>>,还有另一种方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 int [] 添加到ArrayList中,如果它没有那个 int [] ,但是由于某种原因,它不起作用.在这种情况下,arrlist是 ArrayList< int []> ,而arrlist是 int [] .该代码位于for循环中,其中在循环中定义了arr,因此arr中的值会更改.即使我打印出arrlist并包含arr,代码也始终会说arrlist不包含arr.还有另一种方法来检查ArrayList是否包含 int [] 吗?

I want to add an int[] to an ArrayList if it doesn't already have that int[], but for some reason, it's not working. In this case, arrlist is the ArrayList<int[]> and arr is the int[]. This code is in a for loop where arr is defined in the loop, so the values in arr changes. Even though I printed out arrlist and it had arr, the code would always say that arrlist didn't contain arr. Is there another way to check if an ArrayList contains an int[]?

int n = scan.nextInt();
ArrayList<int[]> arrlist = new ArrayList<>();
int[][] coordinates = new int[n][2];
boolean[] isTrue = new boolean[n];
for (int j = 0; j < n; j++) {
    int[] arr = new int[2];
    arr[0] = coordinates[j][0];
    arr[1] = coordinates[j][1];
    if (arrlist.contains(arr)) {
        isTrue[j] = true;
    } else {
        arrlist.add(arr);
    }
}

推荐答案

您需要将 arr 中的每个int值与 ArrayList中包含的所有数组的相应int值进行比较arrlist .
最短的解决方案应该是以下lambda:

You need to compare each int-value in arr against the corresponding int-values of all arrays contained in Your ArrayList arrlist.
The shortest solution should be the following lambda:

布尔包含= arrlist.stream().anyMatch(a-> arr [0] == a [0]&& arr [1] == a [1]);

anyMatch 在找到第一个匹配项后立即停止

这篇关于&amp;#39;包含&amp;#39;方法不适用于ArrayList&amp; lt [int []&gt;>,还有另一种方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆