• Post Reply Bookmark Topic Watch Topic
  • New Topic

Adding elements into a two-dimensional array  RSS feed

 
Mark Richardson
Ranch Hand
Posts: 108
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the following array declaration:

Now consider the instantiation of this same array:

Finally, I want to add the following data into my newly created array. How can I do so?
 
Mark Richardson
Ranch Hand
Posts: 108
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I came up with this.... but what doesn't make sense to me is why this way requires no [4] and [3] in my instantiation.  Why is it that the below method isn't requiring an explicit size of the multi-dimensional array and my original post does require it.
What's the point of mentioning the limits/structure of the array if the code below seems to work just fine?

 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try looking in the Java® Language Specification. Briefly, you have hit on the array initialiser, which creates an array object programmatically. That incorporates its own length field and all its elements; I actually prefer array initialisers to what you had in your first post. I think you are right; use array initialisers in preference to filling in arrays line by line if possible.
Two enhancements and two comments:-
  • 1: Since you are declaring and initialising the array on the same line, you are allowed to miss parts out.
  • 2: You are not declaring a size in advance, so your included arrays may be any size. I shall show both features 1 and 2 later on.
  • 3: There ain't no such thing as a 2D array. That is an array of arrays. 2D arrays used to be common in most C implementations, and they had drawbacks like not having set boundaries, and all included arrays being the same size.
  • 4: Using arrays of Strings is a dreadful way to mimic objects. If you weren't trying out arrays, you would create a Course class with lists of tutors.
  • Example showing better indentation (well, I think better), part missed out (line 1), and different sized subarrays (lines 5‑6):-This is a good way to display that array:-
    System.out.println(Arrays.deepToString(myArray));
    And stick to array initialisers; they are good.
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!