java 中byte[] 數組的合並


因工作的需要,在從事 .Net 的開發中接觸到了 Java, 雖然在大學的時候學過一段Java 編程,但並沒有在實際的工作中使用過, Java 和 .Net的C#語法很相似,都是面向對象的,感覺在語法上只有些細微的差異,這里主要介紹以下,將兩個數組合並成的操作,廢話不多說,直接上代碼:

    //System.arraycopy()方法
    public static byte[] byteMerger(byte[] bt1, byte[] bt2){  
        byte[] bt3 = new byte[bt1.length+bt2.length];  
        System.arraycopy(bt1, 0, bt3, 0, bt1.length);  
        System.arraycopy(bt2, 0, bt3, bt1.length, bt2.length);  
        return bt3;  
    } 
    
    // 使用兩個 for 語句
    //java 合並兩個byte數組  
    public static byte[] byteMerger(byte[] bt1, byte[] bt2){  
        byte[] bt3 = new byte[bt1.length+bt2.length];  
	int i=0;
        for(byte bt: bt1){
         bt3[i]=bt;
	 i++;
	}
        
	for(byte bt: bt2){
	  bt3[i]=bt;
	  i++;
	}
        return bt3;  
    } 

 

    // 使用ArrayList方法
    //java 合並兩個byte數組  
    public static byte[] byteMerger(byte[] bt1, byte[] bt2){  
        List result = new ArrayList();
        result.addAll(bt1);
	result.addAll(bt2);
        return result.toArray();  
    } 

 

// 使用 Arrays.copyOf() 方法,但要在 java6++版本中
public static  String[] concat(String[] first, String[] second) {  
  String[] result = Arrays.copyOf(first, first.length + second.length);  
  System.arraycopy(second, 0, result, first.length, second.length);  
  return result;  
}           

 

    

// 使用ArrayUtils.addAll(Object[], Object[])方法,在包apache-commons中
public static  String[] concat(String[] first, String[] second) {  
  String[] both = (String[]) ArrayUtils.addAll(first, second); 
  return result;  
}           

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM