2016-10-22 158 views
-3

我有4個對象放置在一個數組中。如果索引包含任何其他對象,我不能放置它。我應該如何檢查java中數組的某個索引中是否存在元素或沒有任何內容。示例;
我有一個名爲numList的數組,它包含一些值。我想添加另一個數字到索引6.爲此,我必須檢查numList [6]是否包含一個值。如何檢查一個數組的某個索引是否包含一個值

+0

只要它是一個引用類型的數組(像'Object's),測試'null'? –

+0

你的意思是知道數組中某個給定索引處的元素是否已被使用? –

+0

請告訴我們你已經做了什麼。看到你的代碼會很有幫助。 – mangotang

回答

0

在Java中,內置函數以外的其他類型的數組被初始化爲null值。使用循環找null存儲在其中最低指數:

MyObject[] array = new MyObject[mySize]; 
... // Populate some locations in the array, then... 
int placeAt = -1; 
for (int i = 0 ; i != array.length; i++) { 
    if (array[i] == null) { 
     placeAt = i; 
     break; 
    } 
} 
if (placeAt != -1) { 
    // You found the first index with a null 
    array[placeAt] = myNewObject; 
} else { 
    ... // Array has no empty spaces - report an error and/or exit 
} 
0

不要發瘋,只是檢查是否有給定的指標內空,像這樣:

if (array[index] != null) { 
    array[index] = yourObject1; 
} 

等上。如果你已經爲這個位置分配了一些對象,那麼它將不會被清除。

0

您可以在java中使用ArrayList。 您可以通過add()方法將方法直接添加到列表的末尾,並且如果要檢查索引使用indexOf(object o)方法。

相關問題