溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

在java項(xiàng)目中怎么對(duì)數(shù)組進(jìn)行合并

發(fā)布時(shí)間:2020-12-02 15:37:57 來源:億速云 閱讀:101 作者:Leah 欄目:編程語言

在java項(xiàng)目中怎么對(duì)數(shù)組進(jìn)行合并?相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。

需求:兩個(gè)字符串合并(如果想去重復(fù),參考下一篇--數(shù)組去重復(fù)及記錄重復(fù)個(gè)數(shù))

//方法一 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 (因?yàn)槭前褦?shù)組轉(zhuǎn)為集合,其本質(zhì)還是數(shù)組,數(shù)組長度固定不變,但內(nèi)容可以改變)
  // 結(jié)論:雖然可以把數(shù)組轉(zhuǎn)為集合,但是集合長度不能改變

  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] + " ");
  }
//方法二 循環(huán)遍歷
// 兩個(gè)數(shù)組合并
  String[] str1 = {"Hello","world","java"};
  String[] str2 = {"Veriable","syntax","interator"};
  String[] newStr = new String[str1.length+str2.length];
  //newStr = str1;數(shù)組是引用類型
  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);//數(shù)組擴(kuò)容
  System.arraycopy(str2, 0, str1, str1Length, str2length);
  System.out.println(Arrays.toString(str1));

看完上述內(nèi)容,你們掌握在java項(xiàng)目中怎么對(duì)數(shù)組進(jìn)行合并的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI