2016-12-16 85 views
-1

我必須擺脫數組列表中的所有空條目。他們都在最後,因爲我之前調用了刪除方法。因此,當我使用for循環遍歷數組來搜索空節點時(我不確定你稱之爲單個單元格是否令人困惑),但我不能說for(int k = 0; k < arraylist.size(); k++)之類的東西,因爲尺寸降低了。但我仍然需要擺脫空的節點。我該怎麼做呢?由於刪除數組列表中的空條目

for(int k = 0; k < terms.size(); k++) 
{ 
    if((terms.get(k)).length() < 1) // terms is the name of array list and there are null entries at the end of it 
     terms.remove(k); 
} 
+0

我不清楚你的問題。你可以發佈你的代碼和錯誤日誌嗎? –

+0

沒有錯誤,但我會發布代碼 – Andrew

+0

你的'ArrayList'的類型是什麼? – msagala25

回答

0

每次remove被調用時,ArrayList中的尺寸縮小,因此破壞性循環將無法工作。如果保證所有放置在最後的空物品的假設,我認爲您可以搜索第一個空物品的索引,然後在找到的索引上調用subList

int k; 
for(k = 0; k < terms.size(); k++) 
{ 
    if((terms.get(k)).length() < 1) break; 
} 
return terms.subList(0, k) 
+0

編輯了一個愚蠢的複製/粘貼錯誤 –

3

有很多方法可以做。這裏只是一些例子

調整指數

您的迭代的問題是,當你從某些索引中移除元素,這些元素以下將上移。

所以,

for(int k = 0; k < terms.size(); k++) { 
    if((terms.get(k)).isEmpty()) { // use isEmpty() plesae 
     terms.remove(k--); // move k back 1 element, so it points to 
          // correct index after increment of for loop 
    } 
} 

使用iterator

IIRC ArrayList的迭代器支持remove(),所以你可以做

for (Iterator<String> itr = terms.iterator(); itr.hasNext();) { 
    if (itr.next().isEmpty()) { 
     itr.remove(); 
    } 
} 

做過濾,構建一個新的數組列表。

這可能是最簡單的,如果你不真正需要就地拆除

(假設你使用的是Java 8)

terms = terms.stream().filter(s -> ! s.isEmpty()) 
       .collect(Collectors.toList()); 

// or create another list for result, then 
// terms.clear(); terms.addAll(tempList); 
// if you need to change content of terms instead 
0

如果你知道正是要刪除,那麼是什麼你有兩個選擇。

您可以使用List#removeAll去除你控制一個虛擬的集合,它具有增加開銷,你從來沒有使用列表的缺點的所有元素...

stringList.removeAll(Arrays.asList((String)null)); 

...或者你可以使用Java的Stream API並通過Objects.nonNull篩選出所有null元素。

stringList = stringList.stream().filter(Objects::nonNull) 
           .collect(Collectors.toList()); 

這些選項關心集合的長度都不是。