java - Java 哈希集中字符的索引

标签 java hashset

使用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/

相关文章:

java - Java程序需要构造函数吗

java - 从 HashSet 中删除元素

java - Web 应用程序在使用 Glassfish 4.1 的 Eclipse 中运行良好,但在部署到 Tomcat 9 时却不行

java - Ruby 中字符串池的良好实践

java - 如何从按钮获取文本来编辑文本?

java - HashSet cannot be converted to String error with instanceof 运算符

java - 我们可以在 GAME 中使用 Set 或集合作为返回类型吗?

java - ManyToMany 的 JPA Criteria 规范

C# HashSet VS C++ std::unordered_set 自定义类键。 C++ 更慢……不可能。如何达到C#的速度?

c# - 检查一组不断变化的字符串是否包含字符串的最快方法