Two-dimensional non-zero array of elements with zero value

In Java 8, where should I put annotations like @Nullable

/ @NonNull

in order to declare a two-dimensional array of non- null

nullable elements?

When declaring a type (as in the method signature), both

@Nullable Object @NonNull[][]

      

and

@Nullable Object @NonNull[]@NonNull[]

      

are syntactically valid.

Likewise, when defining a value (zero-length array) I can use either

new @Nullable Object @NonNull[0][]

      

or

new @Nullable Object @NonNull[0]@NonNull[]

      

Which version is correct?

+3


source to share


1 answer


When you read the type of an array, you start in parentheses and read forward, and then you read the type of the last element. For example, Object[][]

pronounced "array of object array". This will help you understand that the first pair of brackets denotes the outermost array, and the next pair of brackets denotes all arrays that are elements of the outermost array.

You put the type annotation just before the corresponding type.

Here's an example from the type annotation spec :

@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

      



This way 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-empty array of nullable elements"

Which one you prefer depends on your specification. Just a "two-dimensional array of null

elements with zero value" doesn't provide enough information to know which one you are accessing, but most likely the second one.

(This question is also given in the Annotation FAQ .)

+5


source







All Articles