I have a standard java array, where null
values are used for unassigned or empty spots in the array. How can I tell if there are unassigned values left, i.e. if the array is not full?
views:
137answers:
5As an array as a static size, you could say that an array is always full.
But if you want to know how many null values are in your array, you simply have to go through it.
Object[] array = new Object[10];
int count = 0;
for(Object item : array){
if(item == null)
count++;
}
Or in a specific method :
public int countNulls(Object[] array){
int count = 0;
for(Object item : array){
if(item == null)
count++;
}
return count;
}
And if you're filling you array index by index :
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.
}
if(myarray[myarray.length-1] != null){
System.out.println("Array is full");
}
If "not full" meaning there are null elements in the array, then you would create a method such as
public boolean isFull(Object[] array) {
for (Object element : array)
if (element == null) return false;
}
return true;
}
While I understand your question, I'm a little confused why you are asking it. First, I'll take a stab at the Q itself.
Arrays in Java are of fixed size, so the concept of them being 'full' doesn't make a whole lot of sense. For primitive arrays, the whole array is initialized with the default value for the primitive. Therefore, if you know that the values you are assigning are non-default values, you can walk in from element length-1 checking for default values.
If you have an array of objects, you can check for nulls. Again, this assumes that you aren't assigning nulls at some point in your population (something that is arguably bad practice). Again, you can walk in from the last element of the array, checking as you go.
You can avoid this issue by going with a proper object collection, such as an array list. You can populate as many elements as you need.
Arrays always full, so
public boolean isFull(Object[] array) {
return true;
}