簡體   English   中英

Java在沒有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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM