如何检查Java中是否存在变量?

5 java null primitive

我只想在没有任何东西的情况下写一个变量.到目前为止,这是我的代码.

if (inv[0] == null) {
    inv[0]=map.getTileId(tileX-1, tileY-1, 0);
}
Run Code Online (Sandbox Code Playgroud)

它给了我这个错误:

java.lang.Error: Unresolved compilation problem: 
The operator == is undefined for the argument type(s) int, null
Run Code Online (Sandbox Code Playgroud)

ami*_*mit 9

inv是一个int[],而int不是null,因为它是一个原始而不是引用.
ints在java中初始化为零.


Jon*_*eet 5

我假设inv是一个int[].

数组中没有"现有"值这样的概念.例如:

int[] x = new int[5];
Run Code Online (Sandbox Code Playgroud)

具有完全相同的内容:

int[] x = new int[5];
x[3] = 0;
Run Code Online (Sandbox Code Playgroud)

现在,如果您使用了一个,Integer[]您可以使用空值来表示"未填充"......这就是您想要的吗?

数组总是用要开始的元素类型的默认值填充 - null在引用类型的情况下,例如Integer.