当前位置: 动力学知识库 > 问答 > 编程问答 >

java - 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?

网友答案:

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.

网友答案:

There is no such thing as an "empty" element in a Java array.

So if it's an array of Object you will test with " == null "

but if it's an array of a primitive type and you did not assigned anything to that location, then it will have the value zero,.

So unless you are sure 0 will never be a "valid" value, you cannot just insert in the array at an "empty" location.

see : http://stackoverflow.com/a/286167/4088809

网友答案:

Theres is another question with the answer for yours.

How to check if array indexes are empty and if so check the next? The answer there is:

 for(int i=0;i<newData.length;i++)
    {
        if(newData[i]==0)
            System.out.println("The value at " + i + "is empty");
    }

Optimized for your code(I think you want to to a method like isArrayFilles or something like that):

 for(int i=0;i<newData.length;i++)
    {
        if(newData[i]==0)
            return false;
    }

return true;
网友答案:

Try declaring your array as an object rather than a traditional array. EX:

Object array[] = new Object[size];
网友答案:
if(array.length == 0){
    //array is empty
}

should be enough

分享给朋友:
您可能感兴趣的文章:
随机阅读: