欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java兩個數(shù)組合并為一個數(shù)組的幾種方法

 更新時間:2023年07月19日 15:27:27   作者:SUMMERENT  
這篇文章主要給大家介紹了關(guān)于java兩個數(shù)組合并為一個數(shù)組的幾種方法,最近在寫代碼時遇到了需要合并兩個數(shù)組的需求,文中將每種方法都介紹的非常詳細(xì),需要的朋友可以參考下

1、int[]數(shù)組

int[] a = {1,2,6};
int[] b = {7,8,9};

合并結(jié)果為:

[1, 2, 6, 7, 8, 9] 

2、String[]數(shù)組

String[] a = {"阿","java","so","easy"};
String[] b = {"is","very","good"};

合并結(jié)果為:

[阿, java, so, easy, is, very, good]

方法一:使用for循環(huán)

1、使用兩個for循環(huán)將數(shù)組 a 和數(shù)組 b 中的元素復(fù)制到數(shù)組 c 中

2、第一個for循環(huán)將數(shù)組 a 中的元素復(fù)制到數(shù)組 c 的前半部分

3、第二個for循環(huán)將數(shù)組 b 中的元素復(fù)制到數(shù)組 c 的后半部分

// int[]數(shù)組
int[] c = new int[a.length + b.length];
for (int i = 0; i < a.length; i++) {
    c[i] = a[i];
}
for (int i = 0; i < b.length; i++) {
    c[a.length +i] = b[i];
}
// String[]數(shù)組
String[] c = new String[a.length + b.length];
for (int i = 0; i < a.length; i++) {
    c[i] = a[i];
}
for (int i = 0; i < b.length; i++) {
    c[a.length + i] = b[i];
}

方法二:使用Arrays.copyOf()方法 

1、使用Arrays.copyOf ()方法創(chuàng)建一個新的數(shù)組,并將數(shù)組 a 中的元素復(fù)制到數(shù)組 c 中

2、使用System.arraycopy ()方法將數(shù)組 b 中的元素復(fù)制到數(shù)組 c 的后半部分。

// int[]數(shù)組
int[] c = Arrays.copyOf(a,a.length+b.length);
System.arraycopy(b,0,c,a.length,b.length);
// String[]數(shù)組
String[] c = Arrays.copyOf(a,a.length+b.length);
System.arraycopy(b,0,c,a.length,b.length);

方法三:使用IntStream.concat方法

1、使用Arrays.stream() 方法將數(shù)組 a 和數(shù)組 b 轉(zhuǎn)換為 IntStream對象

2、使用Stream.concat() 方法將這兩個 IntStream對象連接成一個單獨(dú)的流

3、使用 toArray() 方法將連接后的流轉(zhuǎn)換為一個數(shù)組 c

// int[]數(shù)組
int[] c = IntStream.concat(Arrays.stream(a), Arrays.stream(b)).toArray();
// String[]數(shù)組
Object[] c = Stream.concat(Arrays.stream(a), Arrays.stream(b)).toArray();

方法四:使用System.arraycopy()方法

1、第一個System.arraycopy() 方法,將數(shù)組 a 中的元素復(fù)制到數(shù)組 c 的前半部分

2、第二個System.arraycopy() 方法,將數(shù)組 b 中的元素復(fù)制到數(shù)組 c 的后半部分。

方法:System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length);

參數(shù):
src – 源數(shù)組。

srcPos – 源數(shù)組中的起始位置。

dest – 目標(biāo)數(shù)組。

destPos – 目標(biāo)數(shù)據(jù)中的起始位置。

length – 要復(fù)制的數(shù)組元素的數(shù)量

// int[]數(shù)組
int[] c = new int[a.length + b.length];
System.arraycopy(a,0,c,0,a.length);
System.arraycopy(b,0,c,a.length,b.length);
// String[]數(shù)組
String[] c = new String[a.length + b.length];
System.arraycopy(a,0,c,0,a.length);
System.arraycopy(b,0,c,a.length,b.length);

總結(jié)

到此這篇關(guān)于java兩個數(shù)組合并為一個數(shù)組的幾種方法的文章就介紹到這了,更多相關(guān)java兩個數(shù)組合并內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論