简体   繁体   English

这个Java代码如何工作?

[英]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]);
}    

surprised, The output is 0, why Java doesn't check this kind of indexOutOfBound error? 惊讶,输出为0,为什么Java不检查这种indexOutOfBound错误?

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.. shatner [0]是一个数组(大鼠),恰好是长度为4.所以shartner [0] [3]是rat [3],恰好是0 ..

Where do you see an "indexOutOfBound error"? 你在哪里看到“indexOutOfBound错误”? The code does the following: 代码执行以下操作:

  • Initalize an array (size 1) of int arrays (size 1), ie a 2D array, contents are intialized with 0 初始化int数组(大小为1)的数组(大小为1),即2D数组,内容用0初始化
  • Initalize a array of int , size 4, content is intialized with 0 初始化一个int数组,大小为4,内容初始化为0
  • set the single element of the 2D array to the size 4 1D array 将2D数组的单个元素设置为4个1D数组
  • access the last element of the first array in the 2D array, which is 0 访问2D数组中第一个数组的最后一个元素,即0

There is nothing going out of bounds. 什么都没有出界。

The 0th row in the shatner array gets reinitialized to int[4] . shatner数组中的第0行被重新初始化为int[4]

There is no index out of bounds error. 没有索引超出范围的错误。 shatner is an array of arrays. shatner是一个数组数组。 You replaced the first array of length one with a new one of length four. 你用长度为4的新数组替换了第一个长度为1的数组。 So now shatner[0][3] is a perfectly legit place in memory. 所以现在shatner [0] [3]在记忆中是一个完全合法的地方。

It's not that Java doesn't check the IndexOutOfBoundsException. 并不是Java不检查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. 因为这意味着shatner的第0个索引指向长度为4的数组, shatner[0][4]完全有效。

I'm thinking it's because java's arrays are working a bit differently than expected. 我在想它是因为java的数组工作方式与预期不同。 You initialize shatner to [1][1], meaning something like, {{0},{0}} in memory. 您将shatner初始化为[1] [1],意思是内存中的{{0},{0}}

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. 但是,然后为第一个元素分配一个整数,将其转换为内存中的{{0,0,0,0},{0}} ,因此Java正在寻址新分配的索引。

Arrays need not be rectangular in Java. 数组在Java中不一定是矩形的。 This is a jagged array and is perfectly fine. 这是一个锯齿状的阵列,非常好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM