开发者

How does this Java code work?

public static void main(String[] args)
{
    int [][]shatner = new int[1][1];
    int []rat = new int[4];
    shatner[0] = rat;
    System.out.println(shatner[0][3]);
}    

sur开发者_开发技巧prised, The output is 0, why Java doesn't check this kind of indexOutOfBound error?


Don't be surprised. shatner[0] is an array (rat) and happens to be of length 4. So shartner[0][3] is rat[3] which happens to be 0..


Where do you see an "indexOutOfBound error"? The code does the following:

  • Initalize an array (size 1) of int arrays (size 1), i.e. a 2D array, contents are intialized with 0
  • Initalize a array of int, size 4, content is intialized with 0
  • set the single element of the 2D array to the size 4 1D array
  • access the last element of the first array in the 2D array, which is 0


There is nothing going out of bounds.

The 0th row in the shatner array gets reinitialized to int[4].


There is no index out of bounds error. shatner is an array of arrays. You replaced the first array of length one with a new one of length four. So now shatner[0][3] is a perfectly legit place in memory.


It's not that Java doesn't check the IndexOutOfBoundsException. It's that the answer SHOULD be zero. The key line is

shatner[0] = rat;

Since that means that the 0th index of shatner is pointing to an array of length 4, shatner[0][4] is totally valid.


I'm thinking it's because java's arrays are working a bit differently than expected. You initialize shatner to [1][1], meaning something like, {{0},{0}} in memory.

However, you then assign an integer to the first element, turning it into {{0,0,0,0},{0}} in memory, so Java is addressing the newly assigned index.


Arrays need not be rectangular in Java. This is a jagged array and is perfectly fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜