您需要再次修改i
以確保它覆蓋了數組列表的完整序列,或者按照其他答案中所示的順序返回last-> first。
for (int i = 0; i < result.size(); i++) {
if (result.get(i).split("\\s").length != maxLength) {
result.remove(i);
i--; // everything has been moved up in the arraylist
}
}
而且,花費的ArrayList線性的時間來刪除單個元件,如此反覆去除是一個好主意。
要麼使用LinkedList,它可以在迭代過程中在常量時間內移除,或者首先收集HashSet中的元素,然後使用Collection.removeAll(Collection)在最後刪除它們。
對於ArrayList,removeAll方法花費與列表大小成比例的時間乘以參數集合的查找時間。使用HashSet作爲參數應該儘量減少所花費的時間。
如果你只刪除了一些值,任何集合都可能就足夠了。
LinkedList tmpLinkedList = new LinkedList(result);
for (Iterator iter = tmpLinkedList.iterator(); iter.hasNext() {
if (iter.next().split("\\s").length != maxLength))
iter.remove();
}
result.clear();
result.addAll(tmpLinkedList);
或者:
HashSet toRemove = new HashSet();
//for (Iterator iter = myarraylist.iterator(); iter.hasNext() {
for (String s : result) {
if (s.split("\\s").length != maxLength)
toRemove.add(elem);
}
result.removeAll(toRemove);
你到底想幹什麼?您正在測試由字符「\ s」分隔的字符串返回的數組長度。我沒有看到你的字符串列表,但我期望測試語句總是評估1!= maxLength。 – Zach