2016-10-04 22 views
3
List<String[]> data = new ArrayList<>(); 
data.add(new String[]{"bdc", "house2", "car2"}); 
data.add(new String[]{"abc", "house", "car"}); 

我有問題吧:查找值[]

  1. 如何找到例如,有什麼價值,或者如果我有第二個參數abc,我想查找價值house? (我不知道我的第二個論點當然是第一個)。

  2. 如何刪除所有String[]如果我再次例如abc

+1

1.迭代通過列表,發現含有' 「ABC」'的一個,然後看到第二個價值是什麼。類似'for(int i = 0; i Gendarme

+1

要在索引中刪除,您可以執行'List.remove(i);' –

+2

如果您想使用鍵查找/刪除值,則Map將是更好的選擇。 –

回答

2
  1. 要訪問的陣列的給定的索引,使用方括號array[index]知道index去從0array.length - 1
  2. 要在遍歷它時刪除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 
+0

但「清除」清理所有列表?我想清除或擦除索引,其中是「abc」,例如索引1或任何此「abc」,比x – Baker1562

+0

輸出是這樣的: '房子' ' [abc,house,car]' '[bdc,house2,car2]' 第一行是我想要的,但是當我再次打印「data」時,String []''[abc,house,car] '在那裏,所以我需要刪除那個索引,我發現這個詞,在這種情況下,那個「abc」,thanx爲你的幫助 – Baker1562

+0

使用Arrays.toString(myArray) –