作为静态大小的数组,您可以说数组总是满的.
但是如果你想知道你的数组中有多少个空值,你只需要经历它.
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)