[英]How can I check if a variable exists in Java?
我只想在沒有任何東西的情況下寫入變量。 到目前為止,這是我的代碼。
if (inv[0] == null) {
inv[0]=map.getTileId(tileX-1, tileY-1, 0);
}
它給了我這個錯誤:
java.lang.Error: Unresolved compilation problem:
The operator == is undefined for the argument type(s) int, null
inv 是一個int[]
,而int
不能是null
,因為它是一個原語而不是參考。
int
在 java 中被初始化為零。
我假設inv
是一個int[]
。
沒有值“存在”或不在數組中這樣的概念。 例如:
int[] x = new int[5];
與以下內容完全相同:
int[] x = new int[5];
x[3] = 0;
現在,如果您使用Integer[]
,您可以使用 null 值來指示“未填充”...這是您想要的嗎?
Arrays 總是用元素類型的默認值開始填充 - 在Integer
null
我認為inv
是一個int[]
。 您不能將int
與null
進行比較, null
僅適用於引用類型,而不適用於原語。 您必須為其分配某種標志值( 0
很流行,並且在創建數組時默認情況下它將具有的值),或者將inv
改為Integer[]
( Integer
是參考類型,它是null
-有能力的)。
我從錯誤消息中假設inv[]
是int
的數組,並且 java 中的int
不是 object,因此它不能具有null
與每個索引的默認0
進行比較。大批)..
Java 中的原語不能是 null。
嗯... int
是一個原始類型。 那不可能是 null。
您可以檢查數組的大小:
int[] arr = 新的 int[10]; System.out.println(arr.size());
普通的 arrays 的索引從 0 到它們的大小 - 1,並且不能缺少任何值。 因此,在您的代碼中,您要詢問int
類型的第一個成員是否是null
,這不可能發生 - 它是一個數字,或者它會導致ArrayOutOfBoundsException
。
如果你想要一個類似於 PHP 或 JavaScript 的“稀疏數組”,你需要一個Map
:
Map<Integer, Integer> map = new HashMap();
map.put( 1, 324 );
if( map.get( 2 ) == null ) ...
你可以試試這樣的
Integer[] inv = new Integer[10];
inv[0] = 1;
inv[1] = 2;
....
if(inv[3] == null)
{
inv[3] = getSomeValue();
}
該錯誤是因為inv
是一個數組int
,而不是 object 包裝器Integer
。 無論如何,您的數組都會為您初始化。 如果你寫
int[] inv = new int[5];
您將有一個包含 5 個零的數組。
您應該使用一些您知道無效的值自己初始化您的數組(例如,如果您有一個年齡數組,負值將是無效的)。 檢查無效值,如果存在,請替換它。
原始類型無法與 null 進行比較。
您可以測試數字 if > 0 以查看值是否存在:
if(inv[0] <= 0)
{
inv[0]=map.getTileId(tileX-1, tileY-1, 0);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.