可空元素的二维非空数组

Two-dimensional non-null array of nullable elements

在Java 8中,我应该在哪里放置@Nullable/@NonNull类型注释,以便声明一个二维非null数组可空个元素?

声明类型时(如在方法签名中),两者

@Nullable Object @NonNull[][]

@Nullable Object @NonNull[]@NonNull[]

语法上有效。

同样,当定义一个值(一个零长度数组)时,我可以使用任一

new @Nullable Object @NonNull[0][]

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

哪个版本是正确的?

读取数组类型时,从括号开始向前读取,然后最后读取元素类型。例如,Object[][] 读作 "array of array of Object"。 这有助于您理解第一对括号表示最外层数组,下一对括号表示作为最外层数组元素的所有数组。

您在相应类型之前放置了一个类型注释。

这是来自 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

因此,我们可以理解你的例子:

  • @Nullable Object @NonNull[][] 表示 "non-null array of (unspecified) array of nullable elements"
  • @Nullable Object @NonNull[]@NonNull[]表示"non-null array of non-null array of nullable elements"

您更喜欢其中哪一个取决于您的规格。只是 "two-dimensional non-null array of nullable elements" 没有提供足够的信息来了解您指的是哪一个,但很可能是第二个。

(这个问题在 Type annotations FAQ.)