Reputation:
What I would like to do is create a hashmap that uses a tuple as a key. What I have done so far:
HashMap<String, Integer> seen = new HashMap<String, Integer>();
and for the key I use (X+"#"+Y)
with X, Y being integers. So, when I have two integers I just need to search for this string. However, for very large and many X and Y creating large strings instead of a tuple of integers eats up a lot of memory. How could this be done using (X, Y)
and not (X+"#"+Y)
?
Upvotes: 0
Views: 2532
Reputation: 35
You could create your own class called Tuple that overrides Java's hashCode() function (I assume Java's default implementation won't work for this so you'll have to make your own), which you could then use as the key to your Hashmap :)
EDIT: As many people have already mentioned, I forgot to override equals() as well. Here is the implementation including the equals() function.
Something like this should do:
class Tuple {
public Tuple(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
int hash = 17;
hash = 31 * hash + this.x;
hash = 31 * hash + this.y;
return hash;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null) return false;
if (this.getClass() != other.getClass()) return false;
Tuple that = (Tuple) other;
return (this.x == that.x) && (this.y == that.y);
}
private int x;
private int y;
}
Though as previously mentioned, you could just use Java's java.awt.Point :)
Upvotes: 2
Reputation: 524
You could write your own pair class which is probably the preferred way to go about this, but javax.util also has its own Pair class but the implementation is quite sparse so i usually avoid it.
If you do chose to write your own pair class, you must override Object’s hashcode and equals methods
Upvotes: 1