java 数组索引超出范围异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27150321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Array Index out of range exception
提问by Sima R
I want to print out the elements of this multidimensional array but I get the index out of range error.
我想打印出这个多维数组的元素,但我得到索引超出范围错误。
public class test {
public static void main(String[] args) {
int array1[][]={{1,2,3,4},{5},{6,7}};
for (int i=0; i<3;i++){
for (int j=0; j<4;j++){
System.out.println(array1[i][j]);
}
}
}
}
回答by Konstantin Yovkov
The problem is that with the loop, written like this, you assume that the nested arrays are all of length of 4
(and they are not). You'd better do:
问题是,对于像这样编写的循环,您假设嵌套数组的长度都为4
(而它们不是)。你最好这样做:
for (int i=0; i < array1.length;i++) {
for (int j=0; j < array1[i].length;j++) {
...
}
}
回答by Jon Skeet
Yes, because the second "subarray" doesn't have 4 elements. It would be better to do this dynamically:
是的,因为第二个“子数组”没有 4 个元素。动态执行此操作会更好:
// Note preferred syntax for array types - keep all the type info in one place.
int[][] array1 = {{1,2,3,4},{5},{6,7}};
for (int i = 0; i < array1.length; i++) {
for (int j = 0; array1[i].length; j++) {
System.out.println(array1[i][j]);
}
}
This way the iteration count of the inner loop depends on the array being iterated over.
这样,内循环的迭代次数取决于被迭代的数组。
An alternative is to use the enhanced for loop:
另一种方法是使用增强的 for 循环:
for (int[] subarray : array1) {
for (int value : subarray) {
System.out.println(value);
}
}
回答by Cerberussian
2 points regarding the following solution (and the other similar answers):
关于以下解决方案(以及其他类似答案)的 2 点:
for (int i=0; i < array1.length;i++) {
for (int j=0; j < array1[i].length;j++) {
...
}
}
Here it wont make much difference, as the code is very short, but for better performance you should always avoid repeated calculations if the result never changes. array1's length wont change so calculating its length every iteration is not efficient. This would be improved solution.
int array1Length = array1.length; for (int i=0; i < array1Length;i++){ int array1InnerLength = array1[i].length; for (int j=0; j < array1InnerLength;j++){ ... } }
Some people may suggest using
++j
/++i
instead ofi++
andj++
for better performance, you can read more about it here: What is the difference between ++i and i++?. Its not that critical imo, but it improves understanding of the code you're writing.
在这里它不会有太大区别,因为代码很短,但为了获得更好的性能,如果结果永远不会改变,你应该总是避免重复计算。array1 的长度不会改变,因此每次迭代计算其长度效率不高。这将是改进的解决方案。
int array1Length = array1.length; for (int i=0; i < array1Length;i++){ int array1InnerLength = array1[i].length; for (int j=0; j < array1InnerLength;j++){ ... } }
有些人可能会建议使用
++j
/++i
,而不是i++
和j++
获得更好的性能,你可以阅读更多关于它在这里:有什么区别++ i和i ++的区别?. 它不是那么重要的 imo,但它可以提高对您正在编写的代码的理解。