[英]How to add elements to an arraylist in java inside a for loop without concurrentmodificationexception
[英]Java add/remove at the same loop without ConcurrentModificationException
我有以下Java代碼:
if (value instanceof Collection) {
Collection collection = (Collection) value;
Collection updatedObjects = new ArrayList<>();
for (Iterator iterator = collection.iterator(); iterator.hasNext();) {
Object object = iterator.next();
if (object instanceof String) {
iterator.remove();
updatedObjects.add(StringUtils.wrapInSingleQuotes((String) object));
} else if (object instanceof Date) {
iterator.remove();
updatedObjects.add(((Date) object).getTime());
}
}
collection.addAll(updatedObjects);
}
是否有可能以更有效的方式重寫此代碼,以避免分配新的ArrayList
? 如果是這樣,請舉例說明。
擁有不同類型的Collection
是不好的做法,無論如何,您都可以使用Java 8流:
return collection.stream().map(object -> {
if (object instanceof String) {
return StringUtils.wrapInSingleQuotes((String) object);
} else if (object instanceof Date) {
return ((Date) object).getTime();
}
}).collect(Collectors.toList());
您也可以避免在最后一行寫之前調用iterator.remove()
collection.clear();
collection.addAll...
例如,如果由於參數varialble想要更新變量collection
的值,則可以遵循java.util.List.sort
實現中的邏輯。
Object[] updatedObjects = collection.toArray();
//fill the array updatedObjects
ListIterator<E> i = collection.listIterator();//this works only if collection is a list
for (Object e : updatedObjects ) {
i.next();
i.set((E) e);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.