Java usage of HashMap or Map with multidimensional arrays

十年热恋 提交于 2019-12-11 16:34:06

问题


I would like to use HashMaps<String, V> where the value type V should be a two dimensional int array (int[][]).

Map<String,int[][]> map = new HashMap<>();
int[][] a = new int[][]{ {1, 2} };
map.put("test", a);
System.out.println("Test:" + map.containsKey("test"));  // Test: true
System.out.println("key ==== " + map.get("test"));      // Key === [[I@19a8942

I am trying to have a key that access a unique value i.e. a 2-dimensional array, the size of the array is fixed array[1][3], this is constant. Number of keys will grow with time but not the arrays. For example:

Key1 -> [no1, no2, no3]
key2 -> [no4, no5, no6]
  1. I would like to access the array values, now I get an error.
  2. Is there a better way of implementing this?. Ideally I would like it to be sorted by keys.

I am not an expert in Java but after some reading about maps I felt this works best for me.


回答1:


I would like to access the array values, now I get an error.

Not sure what you mean here, but you seem to be on the right track.

System.out.println(map.get("test")[0][1]);
2

Ideally I would like it to be sorted by keys.

You can use a TreeMap, which is sorted on the natural ordering of its keys.




回答2:


Your code does not produce any errors when I run it. However, you may be misinterpreting java's way of handling string representations of arrays as an error.

When you call System.out.println("key ==== " + map.get("test")); it does indeed correctly print the array. However, by default java expresses arrays oddly, especially arrays of arrays (or 2d arrays). You may want to change this to:

//at top of file
import java.util.Arrays;

//deepToString returns a string that expresses nested arrays in a user-friendly format
System.out.println("key ==== " + Arrays.deepToString(map.get("test")));

Which correctly prints

Test:true
key ==== [[1, 2]]


来源:https://stackoverflow.com/questions/17733746/java-usage-of-hashmap-or-map-with-multidimensional-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!