gpt4 book ai didi

java - 使用 ArrayList 时如何查看元素是否已在列表中?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:09:40 26 4
gpt4 key购买 nike

在这种情况下,使用 ArrayList 库中的 public boolean contains(Object o) 不起作用。考虑

ArrayList<int[][]> test = new ArrayList<>();

int[][] one = {
{1,2,3},
{4,5,6}
};
int[][] two = {
{1,2,3},
{4,5,6}
};
int[][] three = {
{9,7,5},
{1,2,4},
{5,6,7}
};

test.add(one);
System.out.println(test.contains(one));
System.out.println(test.contains(two));
System.out.println(test.contains(three));

以上代码返回

true
false
false

有没有办法检查两者之间的相等性并确保没有重复值进入列表?

最佳答案

我知道的最简单的方法是使用 Arrays.deepEquals(Object[], Object[]) 将其提取到一个方法中, 像 -

public static boolean contains(List<int[][]> al, int[][] toFind) {
for (int[][] arr : al) {
if (Arrays.deepEquals(arr, toFind)) {
return true;
}
}
return false;
}

然后你可以像这样测试它

public static void main(String[] args) {
ArrayList<int[][]> test = new ArrayList<int[][]>();
int[][] one = { { 1, 2, 3 }, { 4, 5, 6 } };
int[][] two = { { 1, 2, 3 }, { 4, 5, 6 } };
int[][] three = { { 9, 7, 5 }, { 1, 2, 4 }, { 5, 6, 7 } };
test.add(one);
if (contains(test, two)) {
System.out.println("Found two");
}
}

输出是

Found two

关于java - 使用 ArrayList<int[][]> 时如何查看元素是否已在列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26388638/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com