简体   繁体   中英

Using Map in Java. How to not overwrite Value?

    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?

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.

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.

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]

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

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM