【问题标题】:Replace values in a java collection替换java集合中的值
【发布时间】:2014-12-01 21:07:43
【问题描述】:

我想更改未知类型集合的值。我找到了java.util.Collections.replaceAll,但这仅适用于列表。我帮助自己创建了一个新的集合并添加了更改的元素。

if (o instanceof Collection) {
            Collection<Object> newCollection = (Collection<Object>) o.getClass().newInstance();
            for (Iterator<Object> it = ((Collection<Object>)o).iterator(); it.hasNext(); ) {
                newCollection.add(doSomethingWith(it.next()));
            }

            return newCollection;
}

但我喜欢返回与结果相同的列表。有什么想法吗?

【问题讨论】:

  • 这个怎么样:Collections.replaceAll(new ArrayList(yourCollection), old, new);。如果要返回它,只需在替换之前将新列表保存到变量中即可。

标签: java collections


【解决方案1】:

不幸的是,您不能在不要求集合为特定类型的情况下执行此操作:因为不需要对集合进行排序,所以让您将项目添加到 Collection 的唯一方法是 add,它在集合中未指定的位置。

集合迭代器也不允许您修改集合元素:一些迭代器允许您删除当前项目,但集合迭代器上没有“替换”方法。

ListIterator&lt;T&gt; interface 提供了一个set(T) 方法,但它使您无法使用List&lt;T&gt;,您已经有了解决方案。

请注意,您的方法也不是万无一失的 - 它依赖于传递给它的集合具有可访问的无参数构造函数的假设。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-25
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多