javamultidimensional-array

Why do Java 2D arrays allow holding rows larger than their specified size?


While coding, I noticed an interesting outcome. I created a 2D char array with a declared size of char[10][10]. However, I found that I could assign char arrays with more characters than the specified size to its rows. Let me demonstrate:

char[][] positions = new char[10][10];
for(int i = 0; i < 10; i++) {
   positions[i] = f.readLine().toCharArray();
}

here, if f.readLine().toCharArray() creates an array with more than 10 characters, the 2D array still seems to accept it. When I print out the positions array using a double for-each loop, it even includes the extra characters.

For example, if the input is

aaaaaaaaaa
bbbbbbbbbb
cccccccccc
dddddddddd
eeeeeeeeee
ffffffffff
gggggggggggg - (12 characters long, 2 extra)
hhhhhhhhhh
iiiiiiiiii
jjjjjjjjjj

The output includes all of the exact characters, including the 2 extra ones from gggggggggggg!

I’m not encountering any errors, but I find it interesting that this works since a 2D array isn’t a list and requires set sizes. Does this behavior cause any potential issues, or is it perfectly fine to do this? Just curious, thanks!


Solution

  • The line:

    char[][] positions = new char[10][10];
    

    … is equivalent in every way to the following:

    char[][] positions = new char[10][];
    for (int i = 0; i < 10; i++) {
      positions[i] = new char[10];
    }
    

    positions is just an array, each of whose elements is a char[]. You can overwrite each value as you like.

    Setting positions[i] = ... discards whatever character array happened to be in positions[i] before -- it could even be null -- and replaces it with a reference to a new array.

    Hopefully this makes sense. The new char[10][10] syntax is just convenient syntactic sugar for creating a bunch of new arrays; it is not binding on the dimensions of the inner arrays in future.