• Post Reply Bookmark Topic Watch Topic
  • New Topic

2D Array Question  RSS feed

 
Kenny Johnson
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How can you say this:

Dog [][] theDogs = new Dog[3][];

How come the last [] can be empty? How many will it hold? I dont understand how you can leave that blank. Dont you have to tell the JVM how big you want it?
[ January 01, 2007: Message edited by: Kenny Johnson ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Kenny,

Welcome to JavaRanch!

In Java, there actually isn't such a thing as a "2D array". In some languages (like C, for example) a 2D array is a block of memory laid out like a square, with one cell for each array element. But in Java, all you actually can have is an array of arrays -- i.e., a 1D array whose elements are themselves 1D arrays.

When you say

Dog [][] theDogs = new Dog[3][];

you're creating a one-dimensional array, 3 elements long. Each element is empty (null), but each can hold a one-dimensional array of Dog objects. Those arrays don't exist, though -- you'd have to create them separately. If you say something like

Dog [][] theDogs = new Dog[3][5];

then Java creates those three Dog arrays for you, each 5 elements long, for a total of four array objects (one of them holding references to three others.)

Note that there's actually nothing that says those three Dog arrays have to be the same length -- they can all be different!
 
Kenny Johnson
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you!! :
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!