2016-10-22 148 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)方法。

相关问题