Reputation: 688
for(int i = 0; i < Board.NUM_OF_ROWS; i++) {
for(int j = 0; j < Board.NUM_OF_COLS; j++) {
if(piece.canMove(board, piece.getX(), piece.getY(), i, j)) {
mappedPosition.put(i, j);
}
}
}
In this code, I am trying to add a pair of (x,y) coordinate of a movable Position of a chess "piece".
For example, I was expecting it to add [2,2], [2,4], [3,1], [3,5], [5,1], [5,5], [6,2], [6,4]
But when I use put, it overwrites the Value when it has the same Key. So [2,2] just becomes [2,4] eventually.
How can I get the full list of the pair without overwriting it?
Upvotes: 0
Views: 2592
Reputation: 58812
You can use Apache MultiMap for holding several values per key
MultiMap mhm = new MultiValueMap();
mhm.put(key, "A"); mhm.put(key, "B");
mhm.put(key, "C");
Collection coll = (Collection) mhm.get(key);coll will be a collection containing "A", "B", "C".
Upvotes: 0
Reputation: 491
In that case you can also use a Multimap. The API is similar, but the value is always a Collection.
http://google.github.io/guava/releases/23.0/api/docs/com/google/common/collect/Multimap.html
Upvotes: 0
Reputation: 295
You can, use Guava's Multimap.
Multimap<Integer, String> multimap = ArrayListMultimap.create();
multimap.put(1, "rohit");
multimap.put(1, "jain");
System.out.println(multimap.get(1)); // Prints - [rohit, jain]
Upvotes: 0
Reputation: 44456
Map
uses the unique key identifiers thus it's impossible to have the same key twice and more.
Create the class holding the two coordinate values you need.
public class BoardPoint {
private int x;
private int y;
public BoardPoint(int x, int y) {
this.x = x;
this.y = y;
}
// getters & setters
}
The class above will be useful in case you need to scale: implement more variables or perform some operations over the pair of values. If you need just a POJO (plain-old Java object) the class java.awt.Point
should be enough as @XtremeBaumer said id the comments.
Upvotes: 3
Reputation: 19453
Map by definition is key --> value. And each key can only have one value at each moment. You can either use set when the values are pair of (x,y) or just a list, it depends on how you wish to use this information later.
Upvotes: 0