简体   繁体   English

使用一个对象设置从集合中删除元素的优点

[英]Advantages of removing element from collection as set with one object

I found next code in official java docs : 我在官方java文档中找到了下一个代码:

collection.removeAll(Collections.singleton(element));

I couldn't figure out advantages of this approach. 我无法弄清楚这种方法的优点。 Why not usual element removing? 为什么不通常删除元素?

collection.remove(element);

Thanks! 谢谢!

前者删除集合中所有出现的元素,后者仅删除第一次出现的元素。

Acc. 加。 to docs: 到文档:

consider the following idiom to remove all instances of a specified element, e, from a Collection, c 考虑以下习惯用法从集合c中删除指定元素e的所有实例

collection.removeAll(Collections.singleton(element));

while collection.remove(element); collection.remove(element); removes a single instance of the specified element from this collection 从此集合中删除指定元素的单个实例

So, to remove all instances, you've to use a loop construct with latter approach. 因此,要删除所有实例,您必须使用后一种方法的循环结构。 while with first one it's just one line job. 而对于第一个,它只是一个线工作。

From the API 来自API

remove(Object o) 删除(对象o)
Removes a single instance of the specified element from this collection, if it is present 从此集合中删除指定元素的单个实例(如果存在)

and: 和:

removeAll(Collection c) removeAll(Collection c)
Removes all of this collection's elements that are also contained in the specified collection 删除也包含在指定集合中的所有此集合的元素

So, if your collection has more than one occurance of the element you wish to remove, you would have to execute collection.remove(element) several times, but removeAll only once. 因此,如果您的集合中有多个要删除的元素,则必须多次执行collection.remove(element),但只能执行一次removeAll。 As removeAll takes a collection as argument, Collection.singleton can offer you a convenient way to create a collection with only one argument. 由于removeAll将集合作为参数,Collection.singleton可以为您提供一种只使用一个参数创建集合的便捷方法。

When testing(unit testing). 测试时(单元测试)。 Collections.singleton is a one line way to turn your subject into a collection. Collections.singleton是将主题转换为集合的一种方式。 The alternative is two lines and not onerous. 另一种选择是两条线而不是繁重的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM