Java 检查哈希集是否包含特定子集
我有一段代码,其中包含Java 检查哈希集是否包含特定子集,java,algorithm,hashset,Java,Algorithm,Hashset,我有一段代码,其中包含 Collection<String> tok=Arrays.asList(tokens); HashSet<String> lookup=new HashSet<String>(); while(!lookup.containsAll(tok)&&max<N) { } 输出是 tokens are [this, a, test, prog
Collection<String> tok=Arrays.asList(tokens);
HashSet<String> lookup=new HashSet<String>();
while(!lookup.containsAll(tok)&&max<N)
{
}
输出是
tokens are [this, a, test, programming]
Increasing Max [is, test, a, this] found =false
Increasing Max [is, test, a, this] found =false
Increasing Max [is, test, a, this] found =false
Increasing Max [is, programming, test, a, this] found =false
Increasing Max [is, programming, test, a, this] found =false
Increasing Max [is, programming, test, a, this] found =false
Increasing Max [is, programming, test, a, this] found =false
Increasing Max [is, programming, test, a, this] found =false
Increasing Max [is, programming, test, a, this] found =false
Increasing Max [is, programming, test, a, this] found =false
Increasing Max [is, programming, test, a, in, this] found =false
Increasing Max [is, programming, test, any, a, in, this] found =false
Increasing Max [is, programming, test, any, a, language, in, this] found =false
No subsegment found
输出显示从未调用remove,但containsAll()仍然返回false,即使它包含集合中存在的所有字符串
为什么即使从未调用过remove,它仍然返回false
即使解决了上述两个问题,哈希集也可能无法工作
This is a this test.
2
this
test
因为索引3处的最小间隔不会添加到集合中。生成的最小间隔将是[0-4],而不是[3-4]
那么,是否有一个集合可能包含重复的值并具有containsAll方法,或者我必须使用带有字符串索引的HashMap作为键?查看pasteBin上的代码,它似乎位于包含
System.out.println(“增加最大值”+lookup.toString()+“found=“+found”)的循环中代码>,,
您从不调用lookup.containsAll(tok)
,也就是说,它在每次循环迭代中输出false
,这是因为found
之前为false
其他几点:
- 不要调用
系统。在代码中退出。(好吧,除非你发现了一个非常严重的异常或错误,你无法从中恢复,这不会发生在你目前试图解决的问题上)
- 如果您事先知道迭代次数,请使用
for
循环。如果您不这样做,特别是如果循环终止依赖于多个变量,则while
循环的可读性会更好
- 要获得问题的简短解决方案(甚至可以在一个屏幕上显示),请查看
清除代码的缩进和换行。现在很难阅读。我已经尝试过正确缩进,但由于我无法立即获得代码的完整视图,我无法查看是否所有行都正确缩进。现在重新检查问题太多了。请每个帖子问一个问题,请参阅和。是的,有4个问题,但1、2和4是非常相关的,它们都与基于哈希的结构的contains方法的一致性有关。我应该将它们移动到不同的帖子吗?@JimGarrison我在此处发布了与此代码无关的问题,将从该帖子中删除它们。我使用HashMap成功地使其工作,但我仍然当输入字符串中不存在子段时,使用System.exit()停止处理,而不是使用另一个标志变量。我搜索了它,发现访问它会导致JEE应用程序中的DOS攻击,但为什么这通常是一种不好的做法?
This is a this test.
2
this
test