我正在使用的:我有多个数组
String[] cat = {"schema cat","schemacat","schemac"}
String[] dog = {"schema dog","schemadog","schemad"}
String[] horse = {"schema horse","schemachorse","schemah"}
我正在为我的方法获取一个值,例如schema cat
,我需要找到它写入的数组。但有时我可以获得 schemac
或 cat
而不是 schema cat
。
问题:所以我需要找到哪个数组包含值。
我尝试过的:我尝试编写多个 if
案例,但它变得困惑和复杂。我想知道这种情况的最佳解决方案是什么。我正在考虑switch,但不知道如何解决case情况。
最佳答案
您可以简单地创建一个方法,在其中给出值
、要查看的不同数组
,然后迭代它们直到找到值
编辑:要获得类似数组的名称,您可以将其添加为数组的第一个值并将其用作返回值
static String whichArrayContains(String value, String[]... arrays) {
for (String[] array : arrays) {
if (Arrays.asList(array).contains(value)) {
return array[0];
}
}
return null;
}
并使用类似
public static void main(String[] args) {
String[] cat = {"car", "schema cat", "schemacat", "schemac"};
String[] dog = {"dog", "schema dog", "schemadog", "schemad"};
String[] horse = {"horse", "schema horse", "schemachorse", "schemah"};
String value = "schema cat";
System.out.println(Arrays.toString(whichArrayContains(value, cat, dog, horse))); // cat
System.out.println(Arrays.toString(whichArrayContains(value, dog, horse))); //null
}
关于Java:多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52187264/