This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Question about filling an Object[][]  RSS feed

 
Sergio Zuniga
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I want to fill an Object[][] with Strings. How can i do it? beacause every time that i've tried it give me an nullPointerException.

thanks
 
Edwin Keeton
Ranch Hand
Posts: 214
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have a NullPointerException because your array, model, is null.

should be something like this:



That should at least get you past your null reference problem.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
While Edwin's post is esentially correct, it looks like you are using the SECOND index for the columns. When this code executes, does the program have both the number of rows and columns? And are there the same number of columns in each row? If so, then you probably need something more like

Notice that I've declared the array as String. If you know all the Objects are actually Strings, you might as well do this, imo. Also, I'm assuming two variables, numRows and numCols, are declared and initialized to the correct number of rows and columns you need in the array.

Also, there is a slight problem with the logic you are using. All but one of the statements inside the for loop start with

This references only a single position in the array, so all the Strings are being placed in the same position! It seems like you really want each String in a different position, so you need to figure out how to do that.

Finally, it may actually be beneficial in this case to create a separate class to store the information you are retrieving here. From the code, it looks like you are getting records from a database. Conceivably, each record can represent an object with the columns as its attributes. (In fact, this is a fairly common way to think about database tables.) You can easily translate this into a Java class with fields for the attributes. Then you can create a one-dimensional array that contains instances of this class. This has the advantage that, when convenient, you can store some of the data as primitive data types, and other data as other objects (such as Strings).

I won't get into further details. If you want to pursue this option, give it a shot on your own and let us know when you encounter problems. I hope this helps answer your questions and gives you some ideas to think about. Let us know how this works out.

Keep Coding!

Layne
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!