Arrays.asList(E[] e)
returns a view of the array as a List
, but when array is null it throws a NullPointerException
.
Arrays.asList(null); //NullPointerException.
Actually I'm doing
List list = possibleNullArray != null ? Arrays.asList(possibleNullArray) : Collections.EMPTY_LIST;
However, creating a Utility class in my project only for this purpose is a thing that I prefer not to do. Is there some utility Class, or library like Apache Commons or Guava to convert null arrays to empty List
? (i.e. a null-safe converter between arrays and Collections).
How would you solve this problem?
No. An ArrayList can be empty (or with nulls as items) an not be null. It would be considered empty.
It is better to return empty collections rather than null when writing methods. The reason being that any code calling your method then doesn't need to explicitly handle a special null case. Returning an empty collection makes the null check redundant and results in much cleaner method calling code.
emptyList() returns an immutable list, i.e., a list to which you cannot add elements if you want to perform any operation on your list, then create new instance of list and return it. if (isValidLang(lang)) { query.
null is a perfectly valid element of an ArrayList. The difference is in the List size, not its capacity. When instantiating a new ArrayList<>(5) , the initial capacity is set to 5, but the size remains 0, because we haven't added any elements.
You can use Java 8 Optional
:
String[] arr = null;
List<String> list = Arrays.asList(Optional.ofNullable(arr).orElse(new String[0]));
You can use Java 8 Optional
and Stream
Optional.ofNullable(possibleNullArray)
.map(Arrays::stream)
.orElseGet(Stream::empty)
.collect(Collectors.toList())
I'm not aware of any util method in Apache Commons / Guava that would create an empty List
instance out of null.
The best thing you can probably do is to initialize the possibly null array beforehand, e.g. with ArrayUtils.nullToEmpty()
. Get rid of the null as soon as you can.
SomeObject[] array = ArrayUtils.nullToEmpty(possiblyNullArray);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With