google/gson · error · NullPointerException
Element must be non-null
Error message
Element must be non-null
What it means
NonNullElementWrapperList is a List wrapper that rejects null elements on mutating operations (set/add). Its nonNull() helper throws NullPointerException('Element must be non-null') when a null is passed (NonNullElementWrapperList.java:53). Read-only query methods like contains/indexOf deliberately permit null arguments.
Solutions
- Filter nulls out of the source collection before adding: list.addAll(src.stream().filter(Objects::nonNull).toList()).
- Replace nulls with a sentinel object if absence must be represented positionally.
- If nulls are valid, do not use NonNullElementWrapperList; use the underlying ArrayList directly.
Example fix
// before wrappedList.add(index, possiblyNull); // after if (possiblyNull != null) wrappedList.add(index, possiblyNull);
Defensive patterns
Strategy: validation
Validate before calling
if (element == null) throw new IllegalArgumentException("null element not allowed"); list.add(index, element); Type guard
static <E> boolean addable(NonNullElementWrapperList<E> l, E e) { return e != null; } Try / catch
try { list.add(i, e); } catch (NullPointerException ex) { /* null element */ } Prevention
- Filter nulls from source collections before addAll on a NonNullElementWrapperList.
- Use Optional or a sentinel object instead of null for absent elements.
- If nulls are valid, do not wrap in NonNullElementWrapperList.
When it happens
Trigger: Calling add(index, null) or set(index, null) on a NonNullElementWrapperList; building such a list from a source that contains nulls via addAll with a null element.
Common situations: Deserializing JSON arrays that include null elements and routing them through a non-null wrapper list; converting between list types where the source permits nulls; legacy code adding optional/sentinel nulls.
Related errors
- key == null
- value == null
- is not Comparable
- Already wrote a name, expecting a value.
- At most one lower bound is supported
AI-assisted analysis of google/gson@310ac341f2 (2026-08-10).
Data as JSON: /api/errors/1f9424faee099cb4.
Report an issue: GitHub.
Appendix: source
Thrown at gson/src/main/java/com/google/gson/internal/NonNullElementWrapperList.java:54
@SuppressWarnings("NonApiType")
public NonNullElementWrapperList(ArrayList<E> delegate) {
this.delegate = Objects.requireNonNull(delegate);
}
@Override
public E get(int index) {
return delegate.get(index);
}
@Override
public int size() {
return delegate.size();
}
private E nonNull(E element) {
if (element == null) {
throw new NullPointerException("Element must be non-null");
}
return element;
}
@Override
public E set(int index, E element) {
return delegate.set(index, nonNull(element));
}
@Override
public void add(int index, E element) {
delegate.add(index, nonNull(element));
}
@Override
public E remove(int index) {
return delegate.remove(index);
}View on GitHub (pinned to 310ac341f2)