Search code examples
javaannotations

Is there a Java annotation for noting that a List may contain nulls?


Is there something like a @ContainsNulls annotation that notes that there may be nulls inside a List?


Solution

  • To specify that a list may contain null elements, declare the list element types using Java's type annotation feature. For example:

    List<@Nullable String> mylist;
    

    Many tools exist for checking nullness, and each one defines its own @Nullable annotation. Many of the tools can read and interpret other tools' annotations.

    Most of the tools make @NonNull the default annotation, so if you just write List<String> the tool interprets that as List<@NonNull String>. This choice reduces the clutter in your code.

    A list of the different tools and their annotations can be found in the Checker Framework manual.

    Some of the tools are bug detectors that find some null pointer exceptions, and others are verification tools that guarantee that your code has no null pointer exceptions. The right tool for you depends on your situation; here is a comparison of the two types of tools.