如何确定数组中是否还有未分配的值?

Lur*_*ron 0 java arrays

我有一个标准的java数组,其中null值用于数组中的未分配或空点.如何判断是否还有未分配的值,即阵列是否未满?

Col*_*ert 5

作为静态大小的数组,您可以说数组总是满的.

但是如果你想知道你的数组中有多少个空值,你只需要经历它.

Object[] array = new Object[10];
int count = 0;
for(Object item : array){
    if(item == null)
        count++;
}
Run Code Online (Sandbox Code Playgroud)

或者以特定方法:

public int countNulls(Object[] array){
    int count = 0;
    for(Object item : array){
        if(item == null)
            count++;
    }
    return count;
}
Run Code Online (Sandbox Code Playgroud)

如果您按索引填充数组索引:

public int nextEmptyIndex(Object[] array){
    int count = 0;
    for(Object item : array){
        if(item == null)
            return count;
        else
            count++;
    }
    return -1; //Return an invalid value or do something to say that there is no empty index.
}
Run Code Online (Sandbox Code Playgroud)