32

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: 预期:<2> 但是是:<1>

并打印

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

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

4

1 回答 1

44

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

链接到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);
}

是的……坏了!

于 2011-12-04T01:46:38.147 回答