java兩個數(shù)組合并為一個數(shù)組的幾種方法
1、int[]數(shù)組
int[] a = {1,2,6}; int[] b = {7,8,9};
合并結果為:
[1, 2, 6, 7, 8, 9]
2、String[]數(shù)組
String[] a = {"阿","java","so","easy"}; String[] b = {"is","very","good"};
合并結果為:
[阿, java, so, easy, is, very, good]
方法一:使用for循環(huán)
1、使用兩個for循環(huán)將數(shù)組 a 和數(shù)組 b 中的元素復制到數(shù)組 c 中
2、第一個for循環(huán)將數(shù)組 a 中的元素復制到數(shù)組 c 的前半部分
3、第二個for循環(huán)將數(shù)組 b 中的元素復制到數(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 中的元素復制到數(shù)組 c 中
2、使用System.arraycopy ()方法將數(shù)組 b 中的元素復制到數(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 轉換為 IntStream對象
2、使用Stream.concat() 方法將這兩個 IntStream對象連接成一個單獨的流
3、使用 toArray() 方法將連接后的流轉換為一個數(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 中的元素復制到數(shù)組 c 的前半部分
2、第二個System.arraycopy() 方法,將數(shù)組 b 中的元素復制到數(shù)組 c 的后半部分。
方法:System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
參數(shù):
src – 源數(shù)組。srcPos – 源數(shù)組中的起始位置。
dest – 目標數(shù)組。
destPos – 目標數(shù)據(jù)中的起始位置。
length – 要復制的數(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);
總結
到此這篇關于java兩個數(shù)組合并為一個數(shù)組的幾種方法的文章就介紹到這了,更多相關java兩個數(shù)組合并內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
JDBC實現(xiàn)數(shù)據(jù)庫增刪改查功能
這篇文章主要為大家詳細介紹了JDBC實現(xiàn)數(shù)據(jù)庫增刪改查功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-07-07java~springboot~ibatis數(shù)組in查詢的實現(xiàn)方法
這篇文章主要介紹了java~springboot~ibatis數(shù)組in查詢的實現(xiàn)方法,需要的朋友可以參考下2018-09-09詳解springboot如何更新json串里面的內(nèi)容
這篇文章主要為大家介紹了springboot 如何更新json串里面的內(nèi)容,文中有詳細的解決方案供大家參考,對大家的學習或工作有一定的幫助,需要的朋友可以參考下2023-10-10