1. 程式人生 > >java 兩個數組合並

java 兩個數組合並

需求:兩個字串合併(如果想去重複,參考下一篇--陣列去重複及記錄重複個數)
//方法一 Arrays類
    String[] a = {"A","B","C"};
    String[] b = {"D","E"};
    // List<String> list = Arrays.asList(a);   --OK
    // List<String> list = Arrays.asList("A","B","C");  --OK
    // list.add("F");  --UnsupportedOperationException
    // list.remove("A"); --UnsupportedOperationException
    // list.set(1,"javaee");--OK (因為是把陣列轉為集合,其本質還是陣列,陣列長度固定不變,但內容可以改變)
    // 結論:雖然可以把陣列轉為集合,但是集合長度不能改變

    List list = new ArrayList(Arrays.asList(a));
    list.addAll(Arrays.asList(b));
    String[] str = new String[list.size()];
    list.toArray(str);    
    for(int x=0;x<str.length;x++){
        System.out.print(str[x] + " ");
    }
//方法二  迴圈遍歷
// 兩個數組合並
    String[] str1 = {"Hello","world","java"};
    String[] str2 = {"Veriable","syntax","interator"};
    String[] newStr = new String[str1.length+str2.length];
    //newStr = str1;陣列是引用型別
    for(int x=0;x<str1.length;x++){
        newStr[x] = str1[x];
    }        
    for(int y=0;y<str2.length;y++){
        newStr[str1.length+y]=str2[y];
    }
    for(int y=0;y<newStr.length;y++){
        System.out.println(newStr[y] + " ");
    }
// 方法三
    String[] str1 = {"Hello","world","java"};
    String[] str2 = {"Veriable","syntax","interator"};
    int str1Length = str1.length;
    int str2length = str2.length;
        
    str1 = Arrays.copyOf(str1, str1Length+str2length);//陣列擴容
    System.arraycopy(str2, 0, str1, str1Length, str2length);
    System.out.println(Arrays.toString(str1));