Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

Java usage of HashMap or Map with multidimensional arrays

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...