初始化阵列很笨拙

时间:2018-05-10 07:48:22

标签: groovy

我目前有代码

static  Collection<Object[]> defineObjects() {
    def myObjects = new Object[2][4]

    myObjects[0] = [object11,object12,object13,object14]
    myObjects[1] = [object21,object22,object23,object24]

    return myObjects;
}

令人讨厌的是我必须定义数组的大小而不是仅仅初始化它。

是否有更优雅的方式来编写此功能?

1 个答案:

答案 0 :(得分:1)

您不必定义数组的大小。请考虑以下两个示例:

import groovy.transform.CompileStatic
import groovy.transform.TypeChecked

@CompileStatic
@TypeChecked
class Objects {

  static void main(String[] args) {
    println defineObjects()
    println defineObjects2()
  }

  static Collection<Object[]> defineObjects() {
    def myObjects = [
      [new Object(), new Object(), new Object()] as Object[],
      [new Object(), new Object(), new Object()] as Object[]
    ]
    return myObjects
  }

  static Object[][] defineObjects2() {
    def myObjects = [
      [new Object(), new Object(), new Object()] as Object[],
      [new Object(), new Object(), new Object()] as Object[]
    ] as Object[][]
    return myObjects
  }
}

如果使用Collection<Object[]>,您只需添加列表并将其转换为Object[]即可。如果是二维数组,则执行相同操作+将最终列表转换为Object[][]

输出

[[java.lang.Object@4667ae56, java.lang.Object@77cd7a0, java.lang.Object@204f30ec], [java.lang.Object@e25b2fe, java.lang.Object@754ba872, java.lang.Object@146ba0ac]]
[[java.lang.Object@4dfa3a9d, java.lang.Object@6eebc39e, java.lang.Object@464bee09], [java.lang.Object@f6c48ac, java.lang.Object@13deb50e, java.lang.Object@239963d8]]