如何检测一组集合是否包含另一个集合?
很奇怪: A 是一个集合,B 是集合的集合:
Set <String> A=new HashSet<String>();
Set <Set<String>> B=new HashSet<Set<String>>();
我向它们添加了一些东西,并且输出
System.out.println(A)
是:
[evacuated, leave, prepc_behind]
输出是
System.out.println(B)
:
[[leave, to, aux], [auxpass, were, forced], [leave, evacuated, prepc_behind]]
可以看出,集合 B 的第三个元素等于集合 A。所以假设
if(B.contains(A)){...}
应该返回 true ,但显然事实并非如此。问题是什么?
更多详情:
Pattern pattern = Pattern.compile("(.*?)\\((.*?)\\-\\d+,(.*?)\\-\\d+\\).*");
for (int i = 0; i < list.size(); i++) {
Set <String> tp = new HashSet<String>();
Matcher m = pattern.matcher(list.get(i).toString());
if (m.find()) {
tp.add(m.group(1).toLowerCase());
tp.add(m.group(2).toLowerCase());
tp.add(m.group(3).toLowerCase());
}
B.add(tp);
}
Set <String> A=new HashSet<String>();
A.add("leave");
A.add("evacuated");
A.add("prepc_behind");
System.out.println(A);
if(B.contains(A)){
System.out.println("B contains A");
}
It is weird:
A is a Set and B is a Set of Sets:
Set <String> A=new HashSet<String>();
Set <Set<String>> B=new HashSet<Set<String>>();
I added things to them and the output of
System.out.println(A)
is:
[evacuated, leave, prepc_behind]
and the output of
System.out.println(B)
is:
[[leave, to, aux], [auxpass, were, forced], [leave, evacuated, prepc_behind]]
as it can be seen, third element of set B equals to set A. So hypothetically
if(B.contains(A)){...}
should return true, but apparently it does not. What is the problem?
More Details:
Pattern pattern = Pattern.compile("(.*?)\\((.*?)\\-\\d+,(.*?)\\-\\d+\\).*");
for (int i = 0; i < list.size(); i++) {
Set <String> tp = new HashSet<String>();
Matcher m = pattern.matcher(list.get(i).toString());
if (m.find()) {
tp.add(m.group(1).toLowerCase());
tp.add(m.group(2).toLowerCase());
tp.add(m.group(3).toLowerCase());
}
B.add(tp);
}
Set <String> A=new HashSet<String>();
A.add("leave");
A.add("evacuated");
A.add("prepc_behind");
System.out.println(A);
if(B.contains(A)){
System.out.println("B contains A");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
基本思想(
setA.contains(setB) == true
)似乎工作得很好:我冒险猜测您在正则表达式中捕获的内容比您想要的更多。
尝试将正则表达式和测试字符串中的匹配都转换为
byte[]
并相互检查它们。The basic idea (
setA.contains(setB) == true
) seems to work fine:I would hazard a guess that you are capturing more in your regular expression then you would like.
Try converting both the match from the regex and the test string to
byte[]
and checking them against each other.如果集合中的某个元素等于 other,则 Set.contains(other) 返回 true。
Set 重写了 equals() 和 hash()。如果两个集合具有相同的元素,Set.equals() 将返回 true。
因此,如果 A2 属于 B,并且 A2 与 A 具有相同的元素,则 B.contains(A) 将返回 true;
Set.contains(other) return true if an element belongs to the set is equals to other.
And Set has override equals() and hash().Set.equals() will return true if both sets has the same elements.
So,if A2 belongs to B,and A2 has the same elements as A,B.contains(A) will return true;