數組合並java
Ⅰ java怎麼將2個數組的數據合並
concat()方法是對字元串的操作,不是對整數或數組。
concat()用法:
String a="abc";
String b="edf";
String c=a.concat(b);
c的值為「abcdef"
數組可以用for循環合並:
public static void main(String[] args){
int a[]={1,7,9,11,13,15,17,19};
int b[]={2,4,6,8,10};
int aL=a.length;
int bL=b.length;
int lenght=aL+bL;
int[] c=new int[lenght];
for(int i=0;i<lenght;i++){
if(i<aL){//
c[i]=a[i];
}
else{
c[i]=b[i-aL];
}
}
for(int i=0;i<c.length;i++){
System.out.print(c[i]+" ");
}
}
Ⅱ java兩個數組合並用for循環
//兩個數組
String[] str1 = {"a","b","c"};
String[] str2 = {"d","e","f"};
//創建一個要接收的數組
String[] str3= new String[str1.length+str2.length];
//先把第一個數組放進去
for(int x=0;x<str1.length;x++){
str3[x] = str1[x];
}
for(int y=0;y<str2.length;y++){
str3[str1.length+y]=str2[y];
}
for(int y=0;y<str3.length;y++){
System.out.println(str3[y] + " ");
}
如有幫助請採納(不懂請提問),可以看我主頁,歡迎來交流學習;
Ⅲ java中怎麼合並兩個數組 簡單明了的
int[]arr1={1,2,3,4,11};
int[]arr2={6,7,8,9,10};
intnewLength=arr1.length+arr2.length;
int[]arr_target=newint[newLength];
//參數:源數組,源數組起始位置,目標數組,目標數組起始位置,復制長度
System.array(arr1,0,arr_target,0,arr1.length);
System.array(arr2,0,arr_target,arr1.length,arr2.length);
//輸出合並後數組
for(inti:arr_target){
System.out.println(i);
}
//排序
Arrays.sort(arr_target);
//輸出排序數組
for(inti:arr_target){
System.out.println(i);
}
//逆序
int[]arr_reverse=newint[newLength];
intflag=0;
for(inti:arr_target){
arr_reverse[newLength-flag-1]=i;
flag++;
}
//輸出逆序數組
for(inti:arr_reverse){
System.out.println(i);
}
數組合並不一定非得遍歷
具體的輸出題主自己再修改吧
Ⅳ java中面向對象要求合並兩個同類型的數組生成一個新數組
參考邏輯
int len1 = array1.length();
int len2 = array2.length();
// 首先,定義一個新的Object數組
Object[] fullArray = new Object[len1 + len2];
// 拷貝數據
for(int i = 0; i < len1; i++) {
fullArray[i] = array1[i];
}
for(int i = len1; i < len1+len2; i++) {
fullArray[i] = array2[i - len1];
}
Ⅳ java編寫合並兩個數組,{1,2,3,4,5} {4,5,6,7,8}
分為兩步:
1.連接兩個數組.
2.清除重復的元素.
import java.util.Arrays;
public class Combine{
public static void main(String[] args){
int a[]={1,2,3,4,5};
int b[]={4,5,6,7,8};
int temp[]=new int[a.length+b.length];
//連接兩個數組
for(int i=0;i<a.length;i++){
temp[i]=a[i];
}
for(int i=0;i<b.length;i++){
temp[a.length+i]=b[i];
}
//連接數組完成,開始清除重復元素
int size=temp.length;
for(int i=0;i<temp.length;i++){
if(temp[i]!=-1){
for(int j=i+1;j<temp.length;j++){
if(temp[i]==temp[j]){
temp[j]=-1;//將發生重復的元素賦值為-1
size--;
}
}
}
}
int[] result=new int[size];
for(int i=0,j=0;j<size && i<temp.length;i++,j++){
if(temp[i]==-1){
j--;
}
else{
result[j]=temp[i];
}
}
//列印結果
System.err.println(Arrays.toString(result));
}
}