我正在尝试用java编写一个方法来搜索数组中的项目并输出索引。但是,我希望它能够处理不同维度的数组。由于我必须将输入类型声明为 String[][],因此我无法传递 String[] 作为参数。
我想要实现的目标的一个例子:
int[][] my_array1 = {{1, 2}, {3, 4}};
int[] my_array2 = {5,6};
int item1 = 2;
int item2 = 5;
search_item(my_array1, item1);
search_item(my_array2, item2);
输出:
"Index of item1:" [0][1]
"Index of item2:" [0]
我不知道如何做到这一点。我尝试使用通用数组,但到目前为止还不起作用。
提前谢谢您。
最佳答案
这是递归解决方案的草图:
public List<String> findArrayMatches(Object [] input, String pattern) {
List<String> matchingIndices = new ArrayList<>();
for (int i = 0; i < input.length; i++) {
Object elem = input[i];
if (elem instanceof String) {
String elemString = (String)elem;
// check if elemString matches pattern and add index to matchingIndices if it does
} else if (elem instanceof Object[]) {
Object [] elemArray = (Object[])elem;
//recursive call here
List<String> matchingSublevel = findArrayMatches(elemArray, pattern);
//prepend current index to all items of matchingSublevel and add to matchingIndices
} else {
throw new IllegalArgumentException("input is not an array of strings or arrays");
}
}
return matchingIndices;
}
关于此代码的一些注意事项:
- 如您所见,编译器无法检查您的输入数组是否只包含您想要允许的元素,您必须在运行时进行检查
- 一切都依赖于这样一个事实:(在 Java 中)多维数组只是其元素也是数组的数组。
- 此代码还可以处理“奇怪的”多维数组,即在同一级别上混合字符串和数组
- 此解决方案依赖的另一个重要功能是 covariance of arrays ,也就是说任何数组都是
instanceof Object[]
。对于泛型来说,情况并非如此,如果您尝试将新元素插入到input
数组中,则会导致问题。幸运的是你没有。 - 当我在上一点中提到“任何数组”时,这并不完全正确。它是任何不是基元数组的数组,因此它可以与
String[]
一起使用,但不能与int[]
一起使用。我将把它留给您来解决如何使其与int[]
一起工作,因为它可能很繁琐,但对基本原理的增加很少。
关于java - 具有可变维度的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54943353/