Java合並兩個數組或多個數組


/**
     * 將多個數組合並成一個新的數組
     * @param arrays
     * @return
     */
    public static Object[] arrayCopyMerge(Object[]... arrays){
        //數組長度
        int arrayLength = 0;
        //目標數組的起始位置
        int startIndex = 0;

        for(Object[] file : arrays){
            arrayLength = arrayLength + file.length;
        }

        Object[] fileArray = new Object[arrayLength];

        for(int i = 0; i < arrays.length; i++){

            if(i > 0){
                //i為0 時,目標數組的起始位置為0 ,i為1時,目標數組的起始位置為第一個數組長度
                //i為2時,目標數組的起始位置為第一個數組長度+第二個數組長度
                startIndex = startIndex + arrays[i-1].length;
            }
       //復制一個新的數組
            System.arraycopy(arrays[i], 0, fileArray, startIndex, arrays[i].length);

        }
        return fileArray;
    }

 


免責聲明!

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



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