用Java加入两个数组?

可能重复:
如何在Java中连接两个数组?

我有两个对象

HealthMessage[] healthMessages1; HealthMessage[] healthMessages2; HealthMessage[] healthMessagesAll; healthMessages1 = x.getHealth( ); healthMessages2 = y.getHealth( ); 

我应该如何加入这两个对象,所以我只能返回一个:

 return healthMessagesAll; 

推荐的方式是什么?

使用Apache commons collecion API是一种很好的方法:

 healthMessagesAll = ArrayUtils.addAll(healthMessages1,healthMessages2); 

我将分配一个数字,其中包含healthMessages1healthMessages2的总长度,并使用System.arraycopy或两个for循环来复制其内容。 以下是System.arraycopy的示例:

 public class HelloWorld { public static void main(String []args) { int[] a = new int[] { 1, 2, 3}; int[] b = new int[] { 3, 4, 5}; int[] r = new int[a.length + b.length]; System.arraycopy(a, 0, r, 0, a.length); System.arraycopy(b, 0, r, a.length, b.length); // prints 1, 2, 3, 4, 5 on sep. lines for(int x : r) { System.out.println(x); } } } 

这样写起来更直观,您不必处理数组索引:

 Collection collection = new ArrayList(); collection.addAll(Arrays.asList(healthMessages1)); collection.addAll(Arrays.asList(healthMessages2)); HealthMessage[] healthMessagesAll = collection.toArray(new HealthMessage[] {}); 

..但与System.arraycopy相比,不要问我它的性能。

我会选择System.arraycopy

 private static HealthMessage[] join(HealthMessage[] healthMessages1, HealthMessage[] healthMessages2) { HealthMessage[] healthMessagesAll = new HealthMessage[healthMessages1.length + healthMessages2.length]; System.arraycopy(healthMessages1, 0, healthMessagesAll, 0, healthMessages1.length); System.arraycopy(healthMessages2, 0, healthMessagesAll, healthMessages1.length, healthMessages2.length); return healthMessagesAll; } 

怎么样这样的事情:

  List l1 = Arrays.asList(healthMessages1); l1.addAll(Arrays.asList(healthMessages2)); HealthMessage[] result = l1.toArray(); 

(需要一点凝聚…… 🙂

数组是固定长度的,所以你有各种各样的选择。 这是一对夫妇:

a)创建一个具有其他大小的新数组,并手动复制所有元素。

 healthMessagesAll = new HealthMessage[healthMessages1.length + healthMessages2.length]; int i = 0; for (HealthMessage msg : healthMessases1) { healthMessagesAll[i] = msg; i++; } for (HealthMessage msg : healthMessages2) { healthMessagesAll[i] = msg; i++; } 

b)使用Arrays类提供的方法。 您可以将数组转换为List,或批量复制元素。 看看它提供的function,并选择适合您的function。

UPDATE

查看有关重复的评论。 您可能希望将所有内容放在一个保证唯一性的Set中。 如果两次添加相同的元素,则不会再次添加。 如果您明确要求具有自己的toArray()方法的数组,则可以将Set转换回数组。

正如其他受访者所建议的那样, System.arraycopy()也可以帮助您复制元素的内容,因此它是我上面的替代(a)的较短版本。

对于最复杂但内存最少的解决方案,您可以将它们包装在一个对象中。 这个提供了跨所有项目的Iterator和复制到新数组的copyTo方法。 它可以很容易地增强,以提供getter和setter。

 public class JoinedArray implements Iterable { final List joined; // Pass all arrays to be joined as constructor parameters. public JoinedArray(T[]... arrays) { joined = Arrays.asList(arrays); } // Iterate across all entries in all arrays (in sequence). public Iterator iterator() { return new JoinedIterator(joined); } private class JoinedIterator implements Iterator { // The iterator across the arrays. Iterator i; // The array I am working on. Equivalent to i.next without the hassle. T[] a; // Where we are in it. int ai; // The next T to return. T next = null; private JoinedIterator(List joined) { i = joined.iterator(); a = nextArray(); } private T[] nextArray () { ai = 0; return i.hasNext() ? i.next() : null; } public boolean hasNext() { if (next == null) { // a goes to null at the end of i. if (a != null) { // End of a? if (ai >= a.length) { // Yes! Next i. a = nextArray(); } if (a != null) { next = a[ai++]; } } } return next != null; } public T next() { T n = null; if (hasNext()) { // Give it to them. n = next; next = null; } else { // Not there!! throw new NoSuchElementException(); } return n; } public void remove() { throw new UnsupportedOperationException("Not supported."); } } public int copyTo(T[] to, int offset, int length) { int copied = 0; // Walk each of my arrays. for (T[] a : joined) { // All done if nothing left to copy. if (length <= 0) { break; } if (offset < a.length) { // Copy up to the end or to the limit, whichever is the first. int n = Math.min(a.length - offset, length); System.arraycopy(a, offset, to, copied, n); offset = 0; copied += n; length -= n; } else { // Skip this array completely. offset -= a.length; } } return copied; } public int copyTo(T[] to, int offset) { return copyTo(to, offset, to.length); } public int copyTo(T[] to) { return copyTo(to, 0); } @Override public String toString() { StringBuilder s = new StringBuilder(); Separator comma = new Separator(","); for (T[] a : joined) { s.append(comma.sep()).append(Arrays.toString(a)); } return s.toString(); } public static void main(String[] args) { JoinedArray a = new JoinedArray( new String[]{ "One" }, new String[]{ "Two", "Three", "Four", "Five" }, new String[]{ "Six", "Seven", "Eight", "Nine" }); for (String s : a) { System.out.println(s); } String[] four = new String[4]; int copied = a.copyTo(four, 3, 4); System.out.println("Copied " + copied + " = " + Arrays.toString(four)); } }