JAVA ArrayList:如何知道它是否包含字符串数组? [英] JAVA ArrayList : How to know whether it contains a String array or not?
问题描述
import java.util.ArrayList;
public class Test {
public static void main (String[] args){
ArrayList<String[]> a = new ArrayList<String[]>();
a.add(new String[]{"one", "abc"});
a.add(new String[]{"two", "def"});
if(a.contains(new String[]{"one", "abc"})){
System.out.println(true);
}else{
System.out.println(false);
}
}
}
控制台说错误".我有一个 ArrayList,但无法检查它是否包含特定的 String 数组.怎么做,为什么?
Console said "false." I have an ArrayList and I can't check whether it contains a particular String array. How to do and why?
推荐答案
contains
使用 equals
方法实现检查对象相等性.然而,对于数组,equals
等效于引用相等.IE.array1.equals(array2)
转换为 array1 == array2
.
contains
checks object equality using the equals
method implementation. For arrays, however, equals
is equivalent to reference equality. I.e. array1.equals(array2)
translates to array1 == array2
.
在上面,new String[]{"one", "abc"})
传递给contains
方法会创建一个newem> 数组,它将与最初添加到 ArrayList
中的数组不同.
In the above, the new String[]{"one", "abc"})
passed to the contains
method will create a new array which will be different than the one originally added to the ArrayList
.
进行检查的一种方法是遍历 ArrayList
中的每个数组,并使用 Arrays.equals(array1, array2)
来检查相等性:
One way to do the check is to loop over each array in the ArrayList
and check the equality using Arrays.equals(array1, array2)
:
for(String[] arr : a) {
if(Arrays.equals(arr, new String[]{"one", "abc"})) {
System.out.println(true);
break;
}
}
另一种方法是使用 ArrayUtils.isEquals
来自 Apache commons-lang
.
这篇关于JAVA ArrayList:如何知道它是否包含字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!