开发者

Java map with 2D boolean array as values

开发者 https://www.devze.com 2023-02-04 08:30 出处:网络
Hello suppose I have a hashmap HashMap<Integer,boolean[][]> map= new HashMap(); How do I put a true or fa开发者_Go百科lse value on the map in the 2d arrayHashMap<Integer, boolean[][]> ma

Hello suppose I have a hashmap

HashMap<Integer,boolean[][]> map= new HashMap();

How do I put a true or fa开发者_Go百科lse value on the map in the 2d array


HashMap<Integer, boolean[][]> map = new HashMap();
int rowNumber = 1;
boolean[][] array2D = map.get(rowNumber);
array2D[10][20] = true;


//First get the boolean array if it exists.
boolean[][] value = map.get(key);
//If it doesn't exist in the map yet, instantiate it.
if(value == null){
  value = new boolean[size1][size2];
  map.put(key,value);
}
//Set the boolean value in the array at the correct location
value[index1][index2] = booleanValue;

Fill in the key, booleanValue, sizes, and indices as necessary.


Correct me if I'm wrong, but it seems like you want to put straight up boolean values in the map. The way you have it set up, your map is not made up of booleans, but actually of boolean arrays.

That's why you can't just put map.put(key, true) because true is not of the type boolean[][], it is just a plain vanilla boolean. You will probably get a type mismatch error of some kind because booleans can't just magically become arrays unless you tell the computer where to put the boolean in your array.

If you actually meant to make a map where each bucket holds a 2D array, then rfeak's answer will solve your problem.


You mean like this?

int index, row, col = ....
Boolean[][] array = map.get(index);
array[row][col] = true/false;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号