简体   繁体   中英

Can I use the addAll Collection method to add all elements (type:byte) from arrays(byte[]) to a List of type Byte?

I have to append (variable number of) byte arrays. Collections seem to only work with the wrapper classes, ie Byte. After about 20 hours I've came up with this, and it works, but I wondered if it could be improved (ADD TO LIST, but any other improvement suggestions welcome:), ie

Collections.addAll method all the array elements to the specified collection. This is how Collections.addAll method is being called. It does the same as Arrays.asList method however it is much faster than it so performance wise this is a best way to get the array converted to ArrayList.

Here it is in it's current beta version

public static byte[] joinArrays(byte[]... args) {

    List<Byte> arrayList = new ArrayList(); 

    for (byte[] arg : args) { // For all array arguments...
        for (int i = 0; i < arg.length; i++) { // For all elements in array
            arrayList.add(Byte.valueOf(arg[i])); // ADD TO LIST
        }
    }
    byte[] returnArray = new byte[arrayList.size()]; 

    for (int i = 0; i < arrayList.size(); i++) {
        returnArray[i] = arrayList.get(i).byteValue(); //Get byte from Byte List
    }
    return returnArray;
}

You could stick to your arrays and avoid the boxing/unboxing into Byte with something like this:

public static byte[] joinArrays(byte[]... args) {
    int byteCount = 0;
    for (byte[] arg : args) { // For all array arguments...
        byteCount += arg.length;
    }
    byte[] returnArray = new byte[byteCount];
    int offset = 0;
    for (byte[] arg : args) { // For all array arguments...
        System.arraycopy(arg, 0, returnArray, offset, arg.length);
        offset += arg.length;
    }
    return returnArray;
}

Here is one variation

public static byte[] joinArrays(byte[]... args) {
    byte[] result = null; 
    if(args.length > 0) {
        result = args[0];
        for(int index = 1; index < args.length; index++){
            result = concat(result, args[index]);
        }       
    }
    return result;
}   

public static byte[] concat(byte[] a, byte[] b) {
    int aLen = a.length;
    int bLen = b.length;
    byte[] c= new byte[aLen+bLen];
    System.arraycopy(a, 0, c, 0, aLen);
    System.arraycopy(b, 0, c, aLen, bLen);
    return c;
}   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM