java - 如何使用 2 个键在 HashMap 或 ArrayList 上获取或设置值

标签 java android

我想做一些类似的事情

object.set(lineIndex, wordIndex, value);

这个用于检索

value=object.get(lineIndex,wordIndex);

但是ArrayList和HashMap不支持2个键值
任何想法!!
谢谢

最佳答案

创建一个类来存储您要使用的两个键,并将其用作 Map 中的键。它会有一点开销,但应该比嵌套的 HashMap 使用更少的内存。

示例:

class IndexKey{
    public final int lineIndex;
    public final int wordIndex;
    public IndexKey(int lineIndex, int keyIndex){
        this.lineIndex = lineIndex;
        this.wordIndex = wordIndex;
    }

    @Override
    public int hashCode() {
       int hash = 7;
       hash = 97 * hash + lineIndex;
       hash = 97 * hash + wordIndex;
       return hash
    }

    @Override
    public boolean equals(Object obj) {
       if (obj == null) {
          return false;
       }
       if (getClass() != obj.getClass()) {
          return false;
       }
       final IndexKey other = (IndexKey) obj;
       if (this.lineIndex != other.lineIndex) {
          return false;
       }
       if (this.wordIndex != other.wordIndex) {
          return false;
       }
       return true;
    }
}

Map<IndexKey, Object> map = new HashMap<>();

object.set(new IndexKey(lineIndex, keyIndex), value);
value=object.get(new IndexKey(lineIndex, wordIndex));

关于java - 如何使用 2 个键在 HashMap 或 ArrayList 上获取或设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25655930/

相关文章:

Java:并发速度比简单的 for 循环慢

java - JFree图表选择点粗细

java - 有人使用过 waf 来构建 Java 应用程序吗?

java - Android 上的简单 XML - 类 MyArrayList<E> 扩展了 ArrayList<E>?

android - 本地 gradle 仓库镜像

android - 将 JSON 从/assets 文件夹读取到 Android 中的 ArrayList 中?

android - 如何取消android中未显示的通知

java - NumberFormatException 消息没有改变?

android - 主屏幕上的网络应用程序(iphone 风格)?

android - 无法在android studio中创建新项目