使用java时如何获取HashSet中元素的索引?
比方说
HashSet<Character> hs = new HashSet<Character>();
hs.add('s');
hs.add('t');
hs.add('a');
hs.add('c');
// some code
if (hs.contains('a')) {
int a = // need the index of a here from hashset
}
查找的运行时间必须与任何数据结构呈线性。
最佳答案
Set 接口(interface)没有像 indexOf()
方法这样的东西。您确实需要对其进行迭代或使用提供 indexOf()
方法的 List 接口(interface)。
如果您愿意,将 Set 转换为 List 非常简单,只需将 Set 传递给 List 实现的构造函数即可。例如
List<String> nameList = new ArrayList<String>(nameSet);
关于java - Java 哈希集中字符的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52962666/