搜索Java中的2维数组 [英] search a 2 dimensional array in java
问题描述
如何通过一个两维数组搜索[] [名]做一件迭代?
How does one iterate through a two dimensional array search for [ ] [Name]?
在名称找到了该指数应返回,这样我可以在阵列中更改的值。
When the Name is found the Index should be returned so that I can change the values in that array.
[索引] [价值观]
[Index] [Values].
此外,如何语法查找存储的阵列发现的? [] [索引]。遍历指数和设置的值。 [0] [1] =等等。
Also, how does the syntax look for the storing to the array found? [ ] [index]. Loop through index and set a value. [0] [1] = blah.
感谢
推荐答案
有时更容易和更清洁总是把搜索结果在一个单独的方法:
Sometimes it's easier and always cleaner to put the search in a separate method:
private Point find2DIndex(Object[][] array, Object search) {
if (search == null || array == null) return null;
for (int rowIndex = 0; rowIndex < array.length; rowIndex++ ) {
Object[] row = array[rowIndex];
if (row != null) {
for (int columnIndex = 0; columnIndex < row.length; columnIndex++) {
if (search.equals(row[columnIndex])) {
return new Point(rowIndex, columnIndex);
}
}
}
}
return null; // value not found in array
}
这将只返回第一个匹配。如果你需要的所有,收集所有点列表,并在年底返回列表。
This will return the first match only. If you need all, collect all points in a List and return that list at the end.
用法:
private void doSomething() {
String[][] array = {{"one", "1"},{"two","2"}, {"three","3"}};
Point index = find2DIndex(array, "two");
// change one value at index
if (index != null)
array[index.x][index.y] = "TWO";
// change everything in the whole row
if (index != null) {
String[] row = array[index.x];
// change the values in that row
}
}
这篇关于搜索Java中的2维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!