7

The javadoc of ArrayUtils.isNotEmpty() in Apache Commons Lang seems to be wrong. Or, at least, misleading. It says

Returns: true if the array is not empty or not null

In my understanding, an empty array is not null. So, according to the above definition, isNotEmpty() should return true for an empty array, which is counterintuitive.

Wouldn't

Returns: true if the array is not null and not empty

be more correct?

Magnilex
  • 11,584
  • 9
  • 62
  • 84
Ulrich Scholz
  • 2,039
  • 4
  • 30
  • 51
  • Are you going to say which `ArrayUtils` are you talking about? There is no such class in Java API. – Rohit Jain Jan 21 '14 at 09:49
  • Sorry, forgot to say. It's `ArrayUtils` from [org.apache.commons.lang](http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/ArrayUtils.html), both version 2.6 and 3.2.1 – Ulrich Scholz Jan 21 '14 at 15:34
  • Seems like it was an issue only until 3.4 Has been fixed since 3.5 – Rishi Dua Oct 21 '19 at 18:19

2 Answers2

5

Wouldn't

Returns: true if the array is not null and not empty

be more correct?

Yes you are right. The doc is a bit misleading. In fact, if you see the source code, it does exactly that:

public static boolean isNotEmpty(Object[] array) {
   return (array != null && array.length != 0);
}
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
0

In my understanding, an empty array is not null.

Not correct. Counterexample:

int a[];

a is an empty array (as it doesn't contain anything), and it's also null since it wasn't initialized.

In this case, isNotEmpty will return false, since it is empty.

Maroun
  • 94,125
  • 30
  • 188
  • 241
  • Sorry but I've to completely disagree with your *empty array* point. `int[] a` is not an empty array, because there is no array at all. – Rohit Jain Jan 21 '14 at 09:59
  • @RohitJain If you pass `a` to a method that expects an array, it'll be fine.. So what is `a`? Just a reference? – Maroun Jan 21 '14 at 10:00
  • Yeah, but that reference should point to an array, which should not be empty. Now, as it is pointing to a non-empty array, it cannot be `null`. Frankly speaking, OP is right. The doc comment is wrong, and not consistent with the code. See my answer. – Rohit Jain Jan 21 '14 at 10:02
  • @RohitJain Thanks for your remark, I'll further investigate this. – Maroun Jan 21 '14 at 10:03
  • @RohitJain So in words, if I write `int a[];`, what you say `a` is? How is it differ from `String b;`? (Both are not initialized) – Maroun Jan 21 '14 at 10:09
  • Yeah, both are references initialized to `null` by default. – Rohit Jain Jan 21 '14 at 10:10
  • 1
    @RohitJain No `int a[];` and `String b;` are not initialized to `null`. Simply aren´t initialized, if you try to use them you will get a compiler error 'The local variable a may not have been initialized' – Rafael Membrives Sep 01 '16 at 12:04