我有一个2D数组,想要使用contains方法来检查myChar是否属于myArray [i] [0]
public static final String[][] myArray = {
{"NM1", "DESC1"},
{"NM2", "DESC2"},
{"NM3", "DESC3"},
{"NM4", "DESC4"},
{"NM5", "DESC5"}
}
Arrays.asList(myArray).contains(mychar);
然而,这对我来说是失败的。当我把它作为一维数组时:
public static final String[][] myArrayNm = {
"NM1",
"NM2",
"NM3",
"NM4",
"NM5"
}
Arrays.asList(myArrayNm).contains(mychar);
正在为我工作。有没有办法可以使用2D数组进行值检查(循环将是最后一个选项)
答案 0 :(得分:2)
试试这个:
public static final String[][] myArray = {
{"NM1", "DESC1"},
{"NM2", "DESC2"},
{"NM3", "DESC3"},
{"NM4", "DESC4"},
{"NM5", "DESC5"}
}
List<String[]> list = Arrays.asList(myArray);
for(String[] arr: list){
System.out.println(Arrays.asList(arr).contains("myString"));
}
不是真正的高效,但它有效:)
答案 1 :(得分:0)
问题在于,当您将2D数组转换为列表时,您将创建一个列表,其中元素是数组,而不是字符串。
答案 2 :(得分:0)
试试这个
List<String> list = new ArrayList<String>();
for (String[] array : myArray) {
list.addAll(Arrays.asList(array));
}
System.out.println(list.contains(mychar));