如何在groovy中组合数组?

Jim*_*d07 20 groovy

存在以下java代码,但我正在尝试将其转换为groovy.我应该像使用System.arraycopy一样保持它,还是groovy有一个更好的方法来组合这样的数组?

  byte[] combineArrays(foo, bar, start) {
    def tmp = new byte[foo.length + bar.length]
    System.arraycopy(foo, 0, tmp, 0, start)
    System.arraycopy(bar, 0, tmp, start, bar.length)
    System.arraycopy(foo, start, tmp, bar.length + start, foo.length - start)
    tmp
  }
Run Code Online (Sandbox Code Playgroud)

谢谢

The*_*ech 41

def a = [1, 2, 3]
def b = [4, 5, 6]

assert a.plus(b) == [1, 2, 3, 4, 5, 6]   
assert a + b     == [1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

  • 我会做一个`(a + b).findAll()` (3认同)
  • 问题是关于数组,而不是列表。 (3认同)

sta*_*229 9

如果要使用数组:

def abc = [1,2,3,4] as Integer[] //Array
def abcList = abc as List
def xyz = [5,6,7,8] as Integer[] //Array
def xyzList = xyz as List

def combined = (abcList << xyzList).flatten()
Run Code Online (Sandbox Code Playgroud)

使用列表:

def abc = [1,2,3,4]
def xyz = [5,6,7,8]
def combined = (abc << xyz).flatten()
Run Code Online (Sandbox Code Playgroud)

  • 这破坏了 abc。如果您需要 abc 及其原始内容,则此解决方案将不起作用。 (2认同)

alt*_*ern 7

def a = [1, 2, 3]
def b = [4, 5, 6]
a.addAll(b)
println a
Run Code Online (Sandbox Code Playgroud)

>> [1, 2, 3, 4, 5, 6]


小智 5

我会去的

byte[] combineArrays(foo, bar, int start) {
  [*foo[0..<start], *bar, *foo[start..<foo.size()]]
}
Run Code Online (Sandbox Code Playgroud)


Bro*_*her 5

诀窍是 flatten() 方法,它将嵌套数组合并为一个:

def a = [1, 2, 3]
def b = [4, 5, 6]
def combined = [a, b].flatten()

assert combined == [1, 2, 3, 4, 5, 6]

println(combined)
Run Code Online (Sandbox Code Playgroud)

要删除空值,您可以像这样使用 findAll():

def a = null
def b = [4, 5, 6]
def combined = [a, b].flatten().findAll{it}

assert combined == [4, 5, 6]

println(combined)
Run Code Online (Sandbox Code Playgroud)