【问题标题】:Java Commons Collections removeAllJava Commons Collections removeAll
【发布时间】:2012-01-12 10:35:45
【问题描述】:

CollectionUtils::removeAll() Commons Collections 3.2.1

我一定要疯了,因为这种方法似乎与文档状态相反:

从集合中移除 remove 中的元素。也就是说,此方法返回一个集合,其中包含 c 中所有不在 remove 中的元素。

这个小小的 JUnit 测试

@Test
public void testCommonsRemoveAll() throws Exception {
    String str1 = "foo";
    String str2 = "bar";
    String str3 = "qux";

    List<String> collection = Arrays.asList(str1, str2, str3);
    System.out.println("collection: " + collection);

    List<String> remove = Arrays.asList(str1);
    System.out.println("remove: " + remove);

    Collection result = CollectionUtils.removeAll(collection, remove);
    System.out.println("result: " + result);
    assertEquals(2, result.size());
}

失败了

java.lang.AssertionError: 预期: 但是是:

和打印

collection: [foo, bar, qux] 
remove: [foo] 
result: [foo]

根据我对文档的阅读,我应该期待 [bar, qux]。我错过了什么?

【问题讨论】:

  • 我更新了我的帖子以反映这一点,因为有人提醒了我 - 但 Apache Commons Collections 4.0 于 2013 年 11 月发布,修复了这个问题。

标签: java collections apache-commons-collection


【解决方案1】:

2014 年 1 月 1 日编辑 Apache Commons Collections 4.0 最终于 2013 年 11 月 21 日发布,其中包含针对此问题的修复程序。

Link to CollectionUtils.java

有问题的行 (1688 - 1691),并确认该方法之前已被破坏:

/*
 ...
 * @since 4.0 (method existed in 3.2 but was completely broken)
 */
public static <E> Collection<E> removeAll(final Collection<E> collection, final Collection<?> remove) {
    return ListUtils.removeAll(collection, remove);
}

原答案

不,你没疯。 removeAll() 实际上(错误地)调用了retainAll()

这是CollectionUtils 中的一个错误,影响版本 3.2。它已被修复,但仅在 4.0 分支中。

https://issues.apache.org/jira/browse/COLLECTIONS-349

作为进一步的证明,这里是源代码的链接:

http://svn.apache.org/repos/asf/commons/proper/collections/tags/COLLECTIONS_3_2/src/java/org/apache/commons/collections/CollectionUtils.java

看看这一行:

public static Collection removeAll(Collection collection, Collection remove) {
    return ListUtils.retainAll(collection, remove);
}

是的……坏了!

【讨论】:

  • 天哪!它是如何从裂缝中溜走的?谢谢(你的)信息。为您投票并接受。
  • @markdsievers - 看起来要么需要单元测试,要么需要修复!
  • IMO,这很糟糕。错误是可以的,但原始问题的创建标记为“02/Aug/06 17:37”,他们仍然没有发布包含修复程序的生产版本。
  • @StephenC - 非常糟糕,即使是补丁发布也比等待主干发布要好,而 Apache Commons Collections 上一次看到发布是 2008 年 4 月的 3.2.1 版。也许没有人认为这是一件大事,或者他们不知道它已经坏了,到处都是代码库的问题。
  • 对于任何感兴趣的人,我的解决方案是直接使用此方法的意图,即 ListUtils.removeAll(a,b)。
猜你喜欢
  • 2016-01-18
  • 1970-01-01
  • 2015-11-19
  • 2013-01-02
  • 1970-01-01
  • 2020-01-25
  • 1970-01-01
  • 1970-01-01
  • 2016-09-03
相关资源
最近更新 更多