Java数组合并方法

参考博客:

https://blog.csdn.net/liu_005/article/details/72760392

https://blog.csdn.net/jaycee110905/article/details/9179227

在做一道算法题的时候用到数组合并,并且有性能要求,这里对Java数组合并进行学习总结。

分析可以得出,因为数组是定长的,所以解决方法,构造一个新数组,将需要合并的数组放到新数组里面。

使用Arrays.copyOf来构造一个合并之后长度的数组,并将其中一个数组放进去,另一个数组的空间填充,

然后调用System.arraycopy()方法,将另一个数组复制到新构造的数组。

也可以直接使用构造函数来构造,然后使用System.arraycopy两次将数组拷贝到构造的数组里。

用到的方法:

  1. System.arraycopy()方法
  2. Arrays.copyOf()方法

API里 System.arraycopy()方法

 API里Arrays.copyOf()方法

 

 数组合并的方法:

public static <T> T[] concat(T[] first, T[] second) {
//构造合并之后的数组,在这里使用Arrays.copy方法,属于合并数组的空间用null填充。 T[] result
= Arrays.copyOf(first, first.length + second.length);
// 将合并数组的数据复制到之前构造好的空间里null填充的数据的位置。 System.arraycopy(second,
0, result, first.length, second.length); return result; }
原文地址:https://www.cnblogs.com/liruilong/p/12235538.html