我有以下 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...
如果你想更新变量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);
}
关于Java 在同一循环中添加/删除,没有 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43322719/