草庐IT

Java Commons Collections removeAll

coder 2023-05-15 原文

CollectionUtils::removeAll() Commons Collections 3.2.1

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

Removes the elements in remove from collection. That is, this method returns a collection containing all the elements in c that are not in 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: expected:<2> but was:<1>

和打印

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

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

最佳答案

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);
}

是的……坏了!

关于Java Commons Collections removeAll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8372576/

有关Java Commons Collections removeAll的更多相关文章

随机推荐