Java中的int a [5],int a [],int a [] = {2,3}之间的区别
我们如何静态声明数组?难道不是int a[5];
?Java中的int a [5],int a [],int a [] = {2,3}之间的区别
package oops;
public class exception {
int arr1[] = new int[10];
public static void main(String args[]){
int a[] ={1,9};
int[] a ;
int a[9];
a[0]=10;
}
}
int a[] = {1,9}
是两个元件1和9 int[] a
被声明一个整数数组称为阵列。未初始化。 int a[9]
是一个包含九个元素的数组。未初始化 int[0]=10
地方值10在位置0处的阵列
'int a [9];'是非法的 –
正确并被删除。 – MaxPower
考虑以下方案
// Create new array with the following two values
int a[] = {1,9};
Assert.assertTrue(2 == a.length);
Assert.assertTrue(1 == a[0]);
Assert.assertTrue(9 == a[1]);
// Create a new, uninitialized array
int[] a;
Assert.assertTrue(null == a);
Assert.assertTrue(0 == a.length); // NullPointerException
int a[9]; // this will not compile, should be
int a[] = new int[9];
Assert.assertTrue(9 == a.length);
Assert.assertTrue(null == a[0]);
// Provided 'a' has not been previously defined
int a[];
a[0] = 10; // NullPointerExcpetion
// Provided 'a' has been defined as having 0 indicies
int a[] = new int[0];
a[0] = 10; // IndexOutOfBoundsException
// Provided 'a' has been defined as an empty array
int a[] = new int[1];
a[0] = 10; // Reassign index 0, to value 10.
“创建一个新的,未初始化的数组”仅当'int [] a'是一个类变量时。如果它是一个局部变量,你会得到一个错误,因为它没有被分配。 –
“'null == a [0]'”不会编译,因为'a [0]'是一个'int'。 –
int arr1[] = new int[10];
上 - >大小为10的一个空数组(存储器分配给它)
int a[] ={1,9};
- > [1,9](创建值为1和9的数组)
int[] a ;
- >已声明但未初始化的数组
int a[9];
- >不工作
参见Arrays
“'的INT A [9];'” 是非法的,因为大小不是类型的一部分。 –