• Post Reply Bookmark Topic Watch Topic
  • New Topic

Null Pointer Exception when Iterating through 2d Array  RSS feed

 
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,
I have a problem with a null pointer exception. I have an array of Objects which is in this example actually 1d (simGrid with row = 1, column = 2) but has to have 2d Capability.
The first position is the BlockZ object. The second Cell the BlockW objects.
The BlockZ Object outputs a Signal of 0 always. The BlockW object is supposed to accept BlockZ's output of 0 with its "leftIn" side, and give it to its "rightOut" side so that another Cell could theoretically accept that value if one was attached to BlockW.
Now there is an update Method that is supposed to realize this signal transfer from Cell to Cell. This is where I get the problem. Upon iterating I get a null pointer exception for simGrid[0][0] where BlockZ is supposed to have been put.

My code:
RealizeGrid class where the update Method calls the BlockW Method to iterate through the array:


The BlockW Class with its own update method:


The BlockZ Class:



And the Main class that executes the creation of these Blocks in the array and then tries to update:



Where am I going wrong? I have tried to find the error but had no luck till now.
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good grief! That amount of code is going to be impossible to read.

You don't have a 2D array because there is no such thing in Java®; you have an array of arrays. And what do you mean about 1D but with the capacity for 2D? I don't think you can create arrays like that.
Whenever you declare an array, fill it as quickly as possible. As you doubtless already know, arrays of reference types are implicitly filled with nulls as the default values. You can use an array initialiser to fill the array. If you have the length of the outer array right, you can replace each of the elements (which is an array) whenever you want.
Foo[][] myArray = {{}, {}, {}, {}, {}};
You now have a 5‑element array of arrays, whose elements each consist of a 0‑length array. No sign of any nulls however hard you look. You can easily replace an element like this:-
myArray[3] = new Foo[]{new Foo(...), new Foo(...), new Foo(...)};
You have now replaced its 4th element with a 3‑element array of Foos.

Go through your code and see where you have declared an array and not initialised it, remembering that all the elements in your array must be initialised, too. Then you can see where you didn't get rid of the nulls. Also show us the stack trace which has all sorts of useful information in, including the line number where the Exception happened.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!