专业的JAVA编程教程与资源

网站首页 > java教程 正文

Java两个Set集合判断是否有交集(java set求并集)

temp10 2024-09-19 04:13:19 java教程 10 ℃ 0 评论

网上很多资料使用retainAll,大致代码如下(这简直误认子弟):

Set<String> set1 = new HashSet<>();
set1.add("A");
set1.add("B");
Set<String> set2 = new HashSet<>();
set2.add("A");
set2.add("B");

boolean hasCommon = set1.retainAll(set2);
System.out.println("s1和s2是否有交集:" + hasCommon);

这简直误认子弟,我们看下retainAll源码的注解

Java两个Set集合判断是否有交集(java set求并集)

Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.
Params:
c – collection containing elements to be retained in this set
Returns:
true if this set changed as a result of the call
Throws:
UnsupportedOperationException – if the retainAll operation is not supported by this set
ClassCastException – if the class of an element of this set is incompatible with the specified collection (optional)
NullPointerException – if this set contains a null element and the specified collection does not permit null elements (optional), or if the specified collection is null
See Also:
remove(Object)

大意是:从此集合中删除未包含在指定集合中的所有元素。如果指定的集合也是一个集合,则此操作有效地修改该集合,使其值是两个集合的交集。

也就是说,从set1 中删除set2中不包含的元素,有删除就返回True。

执行set1.retainAll(set2)以后,set1中剩余的为set1、set2的交集,但返回的结果是True、false并不表示是否有交集,而是表示过程中s1是否有删除元素。(也不知道这是是谁写的,dsx,无力吐槽他的思路)

所以,判断是否有交集需要根据set1执行后的结果,如果执行set1.retainAll(set2)后,set1.size()>0说明有交集,等于0说明没有交集

修改代码为:

Set<String> set1 = new HashSet<>();
set1.add("A");
set1.add("B");
Set<String> set2 = new HashSet<>();
set2.add("A");
set2.add("B");

boolean hasCommon = set1.retainAll(set2);
System.out.println("s1和s2是否有交集:" + (set1.size() > 0));

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表