如何将多个参数映射为 HashMap 中的键?

How can I map by multiple parameters as keys in HashMap?

在我的具体情况下,我想自动缓存修改后的图像 - 我的程序执行一些计算机视觉。为此,它经常对图像重新采样以降低分辨率。这加快了识别速度,同时对我的算法精度几乎没有影响(如果有的话)。但这是一个普遍的问题。

我想要一个包含一个值的多个键的哈希映射。像这样:

//Map images by width and height
protected HashMap<(Integer, Integer), BufferedImage> resampled_images;

当然,上面的语法是无效的。一个糟糕的方法是将参数连接到字符串:

protected HashMap<String, BufferedImage> resampled_images;
...
//Some function that resamples and caches the resampled versions
public BufferedImages getResampled(int new_width, int new_height, boolean cache) {
  ...
  resampled_images.put(new_width+"X"+new_height, resampled_me);
}

仅使用整数参数我认为它会很好用。但在某些情况下,我需要通过更复杂的结构进行索引——而且大多数情况下,它还是会缓存函数结果。图片处理非常CPU昂贵。

编辑: 您可以使用 java.awt.Dimension 对象(或您定义的另一个对象)来存储高度和宽度;

protected HashMap<Dimension, BufferedImage> resampled_images;

例如:

resampled_images.put(new Dimension(width, height), image);

您可以使用以下方案。

Map<height, width> m1;
Map<width, BufferedImage> m2;

允许您创建密钥别名。

这样我相信你可以有一个值 (BufferedImage),与这里的高度和宽度等多个键相关联。

要使用BufferedImage,

m1.put(height,width);
m2.put(width, BufferedImage);

要使用 BufferedImage,

m2.get(m1.get(height)); 

一个Pair<A,B>怎么样class:

class Pair<A,B>{
    A first;
    B second;
}

然后创建一个 HashMap<Pair<Integer,Integer>,BufferedImage> .

编辑:

在您的特殊情况下,实现它的最简单方法是使用基元类型 (int)。您还可以实现 hashCode()equals(Object) 方法,以便 HashMap 可以使用它们。

public class Pair{
    int x,y;

    public Pair(int x,int y){
        this.x = x;
        this.y = y;
    }

    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + x;
        result = prime * result + y;
        return ((x + y) << 234234) % 21354205;
    }

    public boolean equals(Object o){
        if(o instanceof Pair){
            Pair p = (Pair) o;
            return p.x == x && p.y == y;
        }else{
            return false;
        }
    }
}

hashCode()方法是用eclipse生成的