2011-02-04 85 views
13

下面的java代碼存在,但我試圖將其轉換爲groovy。我應該保持它與System.arraycopy一樣嗎?還是groovy有更好的方法來組合這樣的數組?如何在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 
    } 

謝謝

+0

你不使用列表有什麼特別的原因嗎? – 2011-02-04 19:51:03

+0

如果你打算使用數組,我會保持這樣的...沒有任何意義的數組轉換成列表,然後再返回只是使用一些時髦的風格 – 2011-02-05 13:54:45

回答

8

如果你想使用一個數組:

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() 

使用列表:

def abc = [1,2,3,4] 
def xyz = [5,6,7,8] 
def combined = (abc << xyz).flatten() 
+0

這軋液ABC的緣故。如果您需要abc的原始內容,此解決方案將無法工作。 – Jason 2015-03-31 04:12:59

2

這是可以做到這樣的:

def newCombine(foo,bar,start) { 
    ([].add + foo[0..<start]+bar+foo[start..<foo.size()]).flatten() 
} 

它適用於各種陣列(字節[])或列表

+1

我會將您的代碼更改爲 def newCombine(foo,bar,start)def res = [] res << foo [0 .. 2011-02-05 10:15:21

5

我與

byte[] combineArrays(foo, bar, int start) { 
    [*foo[0..<start], *bar, *foo[start..<foo.size()]] 
} 
+0

非常時髦的確。我喜歡!取而代之的foo` – sbglasius 2011-02-05 20:27:37

+1

[開始.. 2011-02-07 10:19:53

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

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

30
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] 
1

所有的解決方案如果上面的失敗去陣列是未定義:

def a = [1,2] 
def b 
assert a+b == [1, 2, null] 

這可能不是你想要的。

def a = [1,2,3,4] 
def b // null array 
def c = [0,4,null,6] 
def abc = [] 
[a,b,c].each{ if (it) abc += it } 
assert abc == [1, 2, 3, 4, 0, 4, null, 6] 

,或者添加所有然後過濾輸出:

(a+b+c).findAll{ it != null } 

(在此假設null不在有效的值,如果添加之前存在

要麼測試陣列原數組,這意味着第一個解決方案是好了很多,即使它可能不看的Groovy不夠。)

0

訣竅是扁平化()方法,即結合d嵌套數組合併爲一個:

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) 

要刪除空值,你可以使用的findAll()這樣的:

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

assert combined == [4, 5, 6] 

println(combined)