简体   繁体   中英

Having trouble calling this weird method (<T>)

Searching online, I found a method I needed that can merge arrays. It was designed to take as many parameters as necessary, and of any datatype. This is what I need it to do, but I don't know how to properly call it! Here's what the method looks like:

public static <T> T[] arrayMerge(T[]... arrays)
{
    blah blah blah
}

The only way I could think of to call it was byte[] result = arrayMerge(a, b, c); (where a, b, and c all refer to byte[]s), but this doesn't work. How can I call it? Thanks!

I think generic types can only work with classes, not primitive types. So, they would work for Byte[] , not byte[] .

You can easily change the method to be non-generic and be specific to byte[] if that is what you want. For example (not sure if it is the best impl):

public static byte[] arrayMerge(byte[]... arrays) {
    int count = 0;
    for (byte[] array : arrays) 
        count += array.length;

    byte[] mergedArray = new byte[count];

    int start = 0;
    for (byte[] array : arrays) {
        System.arraycopy(array, 0, mergedArray, start, array.length);
        start += array.length;
    }
    return mergedArray;
}

Then use:

byte[] result = arrayMerge(new byte[0], new byte[0], new byte[0]);

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