In Java 8, where should I place the @Nullable
/@NonNull
type annotations in order to declare a two-dimensional non-null
array of nullable elements?
When declaring a type (as in method signature), both
@Nullable Object @NonNull[][]
and
@Nullable Object @NonNull[]@NonNull[]
are syntactically valid.
Likewise, when defining a value (a zero-length array), I can use either
new @Nullable Object @NonNull[0][]
or
new @Nullable Object @NonNull[0]@NonNull[]
Which version is correct?
When you read an array type, you start at the brackets and read forward, then read the element type last. For example, Object[][]
is pronounced as "array of array of Object".
This helps you understand that the first pair of brackets denotes the outermost array, and the next pair of brackets denotes all the arrays that are elements of the outermost array.
You put a type annotation immediately before the corresponding type.
Here is an example from the type annotations specification:
@Readonly Document [][] docs1 = new @Readonly Document [2][12]; // array of arrays of read-only documents
Document @Readonly [][] docs2 = new Document @Readonly [2][12]; // read-only array of arrays of documents
Document[] @Readonly [] docs3 = new Document[2] @Readonly [12]; // array of read-only arrays of documents
Thus, we can understand your examples:
@Nullable Object @NonNull[][]
means "non-null array of (unspecified) array of nullable elements"@Nullable Object @NonNull[]@NonNull[]
means "non-null array of non-null array of nullable elements"Which one of these you prefer depends on your specification. Just "two-dimensional non-null
array of nullable elements" doesn't give enough information to know which of these you are referring to, but it's likely the second one.
(This question is also answered in the Type annotations FAQ.)