我有一个包含数组的 arrayList。如何检查 arrayList 是否包含指定的数组?我用过 .contains
方法并返回 false
而不是预期的 true
.
import java.util.ArrayList;
import java.util.Arrays;
public class main {
public static void main(String[] args) {
ArrayList<String[]> action = new ArrayList<String[]>();
action.add(new String[]{"appple", "ball"});
String[] items = new String[]{"appple", "ball"};
if (action.contains(new String[]{"appple", "ball"})) {
System.out.println("Yes");
}
System.out.println(action.contains(items)); // False
}
}
最佳答案
'contains' 方法比较等效的 hashCode 值。
所以如果你像下面那样做它,它就会通过。
public class main {
public static void main(String[] args) {
ArrayList<String[]> action = new ArrayList<String[]>();
String[] items = new String[]{"appple","ball"};
action.add(items);
System.out.println("TO STRING");
System.out.println("--"+action.get(0));
System.out.println("--"+new String[]{"apple","ball"});
System.out.println("HASHCODES");
String[] sameValues = new String[]{"apple","ball"};
System.out.println("--"+action.get(0).hashCode());
System.out.println("--"+items.hashCode());
System.out.println("--"+sameValues.hashCode());
System.out.println("CONTAINS");
System.out.println("--"+action.contains(items)); // *this
System.out.println("--"+action.contains(sameValues));
System.out.println("--"+action.contains(new String[]{"apple","ball"}));
}
}
结果是:TO STRING
--[Ljava.lang.String;@7b1d7fff
--[Ljava.lang.String;@299a06ac
HASHCODES
--1243554231
--1243554231
--2548778887
CONTAINS
--true
--false
--false
关于打印数组时显示的代码,这些不会覆盖
toString()
,所以你得到:getClass().getName() + '@' + Integer.toHexString(hashCode())
例如:
[Ljava.lang.String;@7b1d7fff
[
代表一维数组 Ljava.lang.String
代表类型 @
7b1d7fff
哈希码的十六进制表示 但是,如果要比较值,则有以下方法。
public class main {
public static void main(String[] args) {
String[] items = new String[]{"apple","ball"};
ArrayList<String> action = new ArrayList<>(Arrays.asList(items));
if (action.contains("apple")) {
System.out.println("Yes");
}
}
}
关于java - 检查 arrayList 是否包含数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66361726/