參考博客:
https://blog.csdn.net/liu_005/article/details/72760392
https://blog.csdn.net/jaycee110905/article/details/9179227
在做一道算法題的時候用到數組合並,並且有性能要求,這里對Java數組合並進行學習總結。或者使用工具類實現 apache.commons
import org.apache.commons.lang3.ArrayUtils; 單個多個值得數組插入
分析可以得出,因為數組是定長的,所以解決方法,構造一個新數組,將需要合並的數組放到新數組里面。
使用Arrays.copyOf來構造一個合並之后長度的數組,並將其中一個數組放進去,另一個數組的空間填充,
然后調用System.arraycopy()方法,將另一個數組復制到新構造的數組。
也可以直接使用構造函數來構造,然后使用System.arraycopy兩次將數組拷貝到構造的數組里。
用到的方法:
- System.arraycopy()方法
- 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; }