0

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.

4

2 回答 2

1

当我运行您的代码时,它不会产生任何错误。但是,您可能将 java 处理数组字符串表示的方式误解为错误。

当您调用System.out.println("key ==== " + map.get("test"));它时,它确实正确打印了数组。但是,默认情况下,java 奇怪地表示数组,尤其是数组数组(或 2d 数组)。您可能希望将其更改为:

//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")));

哪个正确打印

Test:true
key ==== [[1, 2]]
于 2013-07-18T21:13:20.707 回答
1

我想访问数组值,现在出现错误。

不知道你在这里的意思,但你似乎在正确的轨道上。

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

理想情况下,我希望它按键排序。

您可以使用 a TreeMap,它按其键的自然顺序排序。

于 2013-07-18T21:02:50.830 回答