在我的具体情况下,我想自动缓存修改后的图像 - 我的程序执行一些计算机视觉操作。为此,它经常对图像进行重新采样以降低分辨率。这加快了识别速度,同时对我的算法精度影响很小(如果有的话)。但这是一个普遍问题。
我想要一个包含一个值的多个键的 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 消耗非常大。
最佳答案
Pair<A,B>
怎么样?类:
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生成的。
关于java - 如何将多个参数映射为 HashMap 中的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29067964/