Jam*_*sev 24 java iteration set
它甚至可能吗?
说你有
private Set<String> names = new LinkedHashSet<String>();
Run Code Online (Sandbox Code Playgroud)
并且Strings是"迈克","约翰","凯伦".
是否有可能在没有迭代的情况下得到"1"以回答"约翰"的索引是什么?
以下工作正常..有了这个问题,我想知道是否有更好的方法
for (String s : names) {
++i;
if (s.equals(someRandomInputString)) {
break;
}
}
Run Code Online (Sandbox Code Playgroud)
Bal*_*usC 23
该Set接口并没有像作为一种indexOf()方法.你真的需要迭代它或者使用提供方法的List接口.indexOf()
如果你想,转换Set到List是很琐碎,它应该是传递的问题Set通过的构造函数List执行.例如
List<String> nameList = new ArrayList<String>(nameSet);
// ...
Run Code Online (Sandbox Code Playgroud)