有人能告诉我为什么我会因为明确地将NULL值设置为数组元素而遇到编译错误?
class array_1
{
public static void main(String args[])
{
int[] a = new int[5];
a[0]=1;
a[2]='a';
a[3]=null; //Compiler complains here
for(int i : a) System.out.println(i);
}
}
我假设因为它的int数组和允许的文字值是0而不是NULL.我对吗 ?
正确.int是一个原始类型,这意味着它包含一个显式值(从-2 ^ 31到2 ^ 31-1的数字),而不是引用,所以它不能null.如果你真的需要null价值观,请使用Integer.
你的数组
int[] a
是原始类型int。基元不能有null值,而是有默认值 0。只有 java 中的对象可以将 null 作为value。原语包括:byte,short,char,int,long,float,double.
| 归档时间: | 
 | 
| 查看次数: | 26700 次 | 
| 最近记录: |