gpt4 book ai didi

java - 为什么我可以在java中创建一个0行5列的二维数组?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:04:41 24 4
gpt4 key购买 nike

int[][] a = new int[0][5];

为什么上面的代码在java中有效?

这个二维数组几乎没有用,因为第一个维度是零。从逻辑上讲,如果第一个维度为 0,则第二个维度不应大于 0。

我知道我们可以启动一个一维空数组。

最佳答案

By the JLS ,指示大小为零的数组表达式是有效的 - 它只是一个表达式 - 因此您可以合法声明基数为零的 n 维数组。

JLS 词法分析器唯一检查的(从 Java 8 开始)是 whether or not the expression evaluates to zero :

Next, the values of the dimension expressions are checked. If the value of any DimExpr expression is less than zero, then a NegativeArraySizeException is thrown.

这并没有说明它的用处,我相信您已经知道,任何对此数组进行索引的尝试都会产生 ArrayIndexOutOfBoundsException,因为您的索引位置从零开始。

关于java - 为什么我可以在java中创建一个0行5列的二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47622885/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com