如何检查数组的某个索引是否包含值

问题描述 投票:0回答:4

我有 4 个对象要放置在一个数组中。如果索引包含任何其他对象,我无法放置它。我应该如何检查java中数组的某个索引中是否有元素或没有元素。示例;
我有一个名为 numList 的数组,它包含一些值。我想向索引 6 添加另一个数字。为此,我必须检查 numList[6] 是否包含值。

java arrays
4个回答
1
投票

不要发疯,只需检查给定索引内是否有 null,如下所示:

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

等等。如果您已经将某个对象分配给该位置,那么它不会被清空。


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
投票

您可以在java中使用ArrayList。 您可以通过 add() 方法直接将方法添加到列表末尾,如果您想检查索引,请使用 indexOf(object o) 方法。


0
投票

由于

if (array[index] != null)
产生
ArrayIndexOutOfBoundsException 
,如果根本不存在这样的元素,那么最好:

for (int i = 0; i < maxSizeOfVariousArrays; i++) {
    if (myArray.length > i) {
        do some stuff with myArray[i];
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.