如何在 java 中连接两个数组?

java 8object oriented programmingprogramming更新于 2025/4/8 9:07:17

一种方法是,创建一个长度等于两个数组长度总和的数组,然后将两个数组的元素逐个添加到其中。

示例

public class HelloWorld {
   public static void main(String[] args) {
      int[]a = {1,2,3,4};
      int[]b = {4,16,1,2,3,22};
      int[]c = new int[a.length+b.length];
      int count = 0;
      for(int i = 0; i<a.length; i++) {
         c[i] = a[i];
         count++;
      }
      for(int j = 0;j<b.length;j++) {
         c[count++] = b[j];
      }
      for(int i = 0;i<c.length;i++)
      System.out.print(c[i]+" ");
   }
}

输出

1 2 3 4 4 16 1 2 3 22

相关文章