1

I am trying to create a 2d array of hashmaps. I do this with the following code:

   @SuppressWarnings("unchecked")
    Map<String, Boolean>[][] arrayBlock3 = (Map <String, Boolean>[][]) new Map[6][6];

When I try to add elements to the array however, at runtime there is a null pointer exception at the first line adding an element to the array.

The code to add an element is:

    arrayBlock3[0][0].put("B", false);
    arrayBlock3[0][1].put("G", false);
    arrayBlock3[0][2].put("B", false);
    arrayBlock3[0][3].put("B", false);
    arrayBlock3[0][4].put("G", false);
    arrayBlock3[0][5].put("B", false); 

Error Message

Exception in thread "main" java.lang.NullPointerException
at main.main(main.java:20)

I would really appreciate your help, thanks.

  • What is `Map`?.. – Maroun Aug 15 '17 at 15:06
  • 1
    Hint: what do you believe the value of `arrayBlock3[0][0]` is, and why? – Jon Skeet Aug 15 '17 at 15:08
  • @JonSkeet I am trying to assign a value to `arrayBlock3[0][0]` and in doing that a null pointer exception is thrown but I am unsure as to why. – StephaneIsGod Aug 15 '17 at 15:34
  • 1
    Nope, you're not trying to assign a value to that array element. You're *fetching* the value of that array element and calling a method on it. The value of the array element is null. – Jon Skeet Aug 15 '17 at 15:34
  • A good rule of thumb when working with arrays is that something has to allocate the array (Usually something like new a[4]) and something has to allocate each element in the array (like new ArrayList()). – Bill K Aug 15 '17 at 16:19

1 Answers1

2

You need to initialize each element in that matrix of Map (and you need to use a class that implements Map, such as HashMap):

for (int i = 0; i < arrayBlock3.length; i++) {
    for (int j = 0; j < arrayBlock3[i].length; j++) {
        arrayBlock3[i][j] = new HashMap<>();
    }
}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Alberto Trindade Tavares
  • 10,056
  • 5
  • 38
  • 46