Reputation: 53149
In my specific case, I wanna automatically cache modified images - my program does some computer vision. For that, it often resamples images to decrease resolution. This speeds up the recognition while having little (if any) impact on my algorithm precision. But this is a general question.
I want to have a hash map that contains multiple keys for one value. Like this:
//Map images by width and height
protected HashMap<(Integer, Integer), BufferedImage> resampled_images;
Of course, syntax above is invalid. A shitty way go around that would be to concatenate parameters to string:
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);
}
With just integer the parameters I think it would work nice. But there are cases I'd need to index by more complex structures - and mostly it would again be caching function results. Image processing is very CPU expensive.
Upvotes: 0
Views: 2907
Reputation: 1262
How about a Pair<A,B>
class:
class Pair<A,B>{
A first;
B second;
}
then create a HashMap<Pair<Integer,Integer>,BufferedImage>
.
EDIT:
In your special case the easiest way to implement it would be with primitives types (int). You could also implement the hashCode()
and equals(Object)
methods, so that the HashMap can use them.
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;
}
}
}
the hashCode()
method is generated with eclipse.
Upvotes: 2
Reputation: 985
You can use following scheme.
Map<height, width> m1;
Map<width, BufferedImage> m2;
Allows you to create key aliases.
That way I believe you can have a value (BufferedImage), associated with multiple keys like height and width here.
To put BufferedImage use,
m1.put(height,width);
m2.put(width, BufferedImage);
To get BufferedImage use,
m2.get(m1.get(height));
Upvotes: 1
Reputation: 1612
EDIT:
You could use a java.awt.Dimension
object (or another object of you definition) to store both height and width;
protected HashMap<Dimension, BufferedImage> resampled_images;
ex:
resampled_images.put(new Dimension(width, height), image);
Upvotes: 0