- 要訪問的陣列的給定的索引,使用方括號
array[index]
知道index
去從0
到array.length - 1
。
- 要在遍歷它時刪除
Collection
的元素,可以使用iterator.remove()
。
所以,你的代碼可能是這樣的:
// Flag used to know if it has already been found
boolean found = false;
for (Iterator<String[]> it = data.iterator(); it.hasNext();) {
String[] values = it.next();
// Check if the first element of the array is "abc"
if (values.length > 1 && "abc".equals(values[0])) {
if (found) {
// Already found so we remove it
it.remove();
continue;
}
// Not found yet so we simply print it
System.out.println(values[1]);
found = true;
}
}
輸出:
house
響應更新:
正如你似乎想要在列表中獲得匹配的索引時,可以簡單地添加一個變量index
,您將在for
循環中增加該值。
int index = 0;
for (Iterator<String[]> it = data.iterator(); it.hasNext();index++) {
...
if (values.length > 1 && "abc".equals(values[0])) {
System.out.printf("abc found at %d%n", index);
...
}
}
輸出:
abc found at 1
house
1.迭代通過列表,發現含有' 「ABC」'的一個,然後看到第二個價值是什麼。類似'for(int i = 0; i
Gendarme
要在索引中刪除,您可以執行'List.remove(i);' –
如果您想使用鍵查找/刪除值,則Map將是更好的選擇。 –