Parfois, il est plus facile et toujours plus propre à mettre la recherche dans une méthode distincte:
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
}
Cela retournera la première correspondance seulement. Si vous avez besoin de tous, collectez tous les points dans une liste et renvoyez cette liste à la fin.
Utilisation:
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
}
}
S'il vous plaît reformuler votre question. "Les tableaux bidimensionnels" en Java sont juste des tableaux de tableaux, donc si vous avez 'String [] [] matrix = ...', alors la première dimension 'matrix [i]' a le type 'String []', pas 'String'. –