javaarraysprimitive-types

How to determine if my array is empty


I need help to check if my array is full or if I can fit more in there. I thought I could check if just one of the positions was empty by doing the following:

    for (int i =0; i <array.length; i++){
        if(array[i] == null){
            return false;
        }else{
            return true;
        }
    }

To test this I created am array with int and got the error: The operator == is undefined for the argument type(s) int, null is there another way I can do this? In my original task I will do this with objects and not int, does this mean it will work with objects but not with int?


Solution

  • Primitive types cannot be null, that's why that does not work. With objects, it will work. In this case, you can use the following code:

    public boolean isArrayFull(Integer[] array) {
        for (Integer i = 0; i < array.length; i++) {
            if (array[i] == null) {
                return false;
            }
        }
        return true;
    }
    

    This also fixes a bug in your code. Your code would return true, if the first element is not null.