Michal Kordas
Michal Kordas

Reputation: 10925

Check that array is empty, but not null

I have an array of objects (Object[] array), and I want to check whether it is empty, but fail fast if it is null with NPE or any other exception.

I know that I can do the following check

array.length == 0

but e.g. in case of String or collections it is not recommended practice, IntelliJ even has inspection for that:

Reports any .size() or .length() comparisons with a 0 literal which can be replaced with a call to .isEmpty().

Is there any replacement for .isEmpty() for arrays?

There is ArrayUtils.html#isEmpty(java.lang.Object[]), but it also checks for null, while I'd like to avoid that.

Upvotes: 4

Views: 2219

Answers (2)

Ken Bekov
Ken Bekov

Reputation: 14015

Because .size() is method, its implementation is hidden. And you can't be sure that this method optimized (there's a possibility, that some collections, for example, enumerate items every time you call .size() method). That is why computing the .size() of collection could be expensive. In the same time, .isEmpty() can checks just is there at least one item in collection, and return result.

But .length is just a field. It does nothing, just returns a value. There are no calculations. This field just stores the length of array with fixed size.

I believe that .size() and .length are totally different things and in this case they can not be compared, as well as collections and arrays.

Upvotes: 4

DonyorM
DonyorM

Reputation: 1800

The easiest way would to be to write such a method yourself. It would be fairly trivial. Something like the following

public boolean isArrayEmpty(Object[] array) {
    if (array == null) {
        //Throw nullpointer exception
        //An easy of method of doing this would be accessing any array field (for example: array.length)
    }
    return (ArrayUtils.isEmpty(array));
}

That being said, there's very little reason why array.length == 0 would be harmful. It's the simplest, cleanest way to do this and does exactly what you want. Most likely part of the reason for ArrayUtils.isEmpty is to allow easy testing of whether or not a array is empty or null, a relatively common need, but you don't want to do that.

Upvotes: 0

Related Questions