java.util.Collection 的经典集合操作 [英] Classical set operations for java.util.Collection

查看:25
本文介绍了java.util.Collection 的经典集合操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java.util.Collection 类上是否有任何内置的经典集合操作功能?我的具体实现将用于 ArrayList,但这听起来应该适用于 Collection 的所有子类.我正在寻找类似的东西:

Is there any built-in functionality for classical set operations on the java.util.Collection class? My specific implementation would be for ArrayList, but this sounds like something that should apply for all subclasses of Collection. I'm looking for something like:

ArrayList<Integer> setA ...
ArrayList<Integer> setB ...
ArrayList<Integer> setAintersectionB = setA.intersection(setB);
ArrayList<Integer> setAminusB = setA.subtract(setB);

经过一番搜索,我只能找到自己开发的解决方案.另外,我意识到我可能将集合"的概念与集合"的概念混淆,分别不允许和允许重复.也许这真的只是 Set 接口的功能?

After some searching, I was only able to find home-grown solutions. Also, I realize I may be confusing the idea of a "Set" with the idea of a "Collection", not allowing and allowing duplicates respectively. Perhaps this is really just functionality for the Set interface?

如果没有人知道任何内置功能,也许我们可以将其用作标准实践 Java 集操作代码的存储库?我想这个轮子已经被重新发明了无数次.

In the event that nobody knows of any built-in functionality, perhaps we could use this as a repository for standard practice Java set operation code? I imagine this wheel has been reinvented numerous times.

推荐答案

Intersection is done with Collection.retainAll;使用 Collection.removeAll 进行减法;与 Collection.addAll 的联合.在每种情况下,因为 Set 将作为一个集合而 List 将作为一个列表.

Intersection is done with Collection.retainAll; subtraction with Collection.removeAll; union with Collection.addAll. In each case, as Set will act like a set and a List will act like a list.

作为可变对象,它们就地操作.如果您想保留原始可变对象不变,则需要显式复制.

As mutable objects, they operate in place. You'll need to explicitly copy if you want to retain the original mutable object unmutated.

这篇关于java.util.Collection 的经典集合操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆