[英]Java add/remove at the same loop without ConcurrentModificationException
I have a following Java code: 我有以下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);
}
Is it possible to rewrite this code in a more efficient way in order to avoid new ArrayList
allocation ? 是否有可能以更有效的方式重写此代码,以避免分配新的
ArrayList
? If so, please show an example. 如果是这样,请举例说明。
Having Collection
of different types is bad practice, anyway you can use Java 8 streams: 拥有不同类型的
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());
Also you can just avoid calling iterator.remove()
and before the last line write 您也可以避免在最后一行写之前调用
iterator.remove()
collection.clear();
collection.addAll...
If you want to update the value of the variable collection
because is a parameter varialble, for example you can follow the logic in java.util.List.sort
implementation. 例如,如果由于参数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.