Make sure the array is empty, but not non-zero.

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

I know I can do the following check

array.length == 0

but, for example, in the case of Stringor collections it is not recommended to practice, IntelliJ even checks for this:

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

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

There is ArrayUtils.html # isEmpty (java.lang.Object []) , but it also checks null, although I would like to avoid it.

+4
source share
2 answers

Since it .size()is a method, its implementation is hidden. And you cannot be sure that this method is optimized (it is likely that some collections, for example, list items every time you call the method .size()). This is why calculating a .size()collection can be expensive. At the same time, it .isEmpty()can check if there is at least one element in the collection and return the result.

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

I believe that .size()and .lengthare completely different things, and in this case they cannot be compared, as well as collections and arrays.

+4
source

- . . -

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));
}

, , array.length == 0 . , , . , ArrayUtils.isEmpty , , , , .

0

Source: https://habr.com/ru/post/1628979/


All Articles