java - ArrayList.removeAll(Collection<>) 关心重复项吗?

标签 java list arraylist collections removeall

假设我定义了一个列表:

List<String> cards = new ArrayList<>();
cards.add("king");
cards.add("queen");
cards.add("king");
cards.add("king");
cards.add("prince");
cards.add("queen");
cards.add("prince");

所以这个ArrayList有3个“国王”String对象、2个“女王”和2个“王子”。 到目前为止一切顺利。

现在我想定义一个新列表:

List<String> toRemove = new ArrayList<>();
toRemove.add("king");
toRemove.add("king");
toRemove.add("queen");
toRemove.add("queen");
toRemove.add("prince");

所以这个ArrayList有2个“国王”、2个“女王”和1个“王子”。 现在,如果我愿意的话:

cards.removeAll(toRemove);

这会考虑重复的对象吗?

如果从卡片列表中减去 toRemove 列表,则应该留下 1 个“国王”、0 个“女王”和 1 个“王子”。对吗?

但是removeAll函数会识别那里有重复的对象,并且不会尝试从卡片中删除所有出现的“国王”,“女王”和“王子”,所以我将留下一个空列表(卡片) ?

最终列表是{"king", "prince"}还是空列表{}?

最佳答案

Java docs 中所述:

removeAll(Collection c)

Removes all of this collection's elements that are also contained in the specified collection (optional operation). After this call returns, this collection will contain no elements in common with the specified collection.

关于java - ArrayList.removeAll(Collection<>) 关心重复项吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60417963/

相关文章:

java - 添加到 ArrayList 后出现 NotSerializedException

java - Spring-ws 或 Axis2 或其他用于 WS 的 "Contract-First"方法

.net - 如何创建通用链表?

java - @Transactional(readOnly=true) 与@QueryHints

java - 获取两个字符串列表中的公共(public)字符串对

python - 如何将整数列表转换为列表列表?

java - 如何计算数组列表中的重复项?

java - 有没有一种简单的方法可以使用 mongo 和 jongo 将 Bson 数组映射到 Java ArrayList?

java - (JAVA)向Binance交易所发送http请求错误

java - 如何使用 Connectivity manager.NetworkCallback 获取网络类型