A HashMap maps one variable to one other variable. You want to use two variables as a key, so you can make a simple Coordinates class.
class Coordinates {
final int x;
final int y;
public Coordinates(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Coordinates other = (Coordinates) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
@Override
public String toString() {
return "<"+x+","+"y"+">";
}
}
In this code, the hashCode
and equals
methods have been generated by Eclipse. All you need to know is that hashCode
generates a number which Map uses as identifier for your coordinate and that equals
checks if two Coordinates point to the same place.
You can then use a Map<Coordinates,String>
for your map. To add something you use:
yourMap.add(new Coordinates(2,3), "A String")
To retrieve something you use
yourMap.get(new Coordinates(2,3)