How to get byte array from list?

I am adding some data to super list and trying to convert that list to byte[], but getting class cast exception. Below is my code.

public byte[] getBytes () {
        Byte[] arrayByte = (Byte[])super.toArray();
        byte [] bytes = Utility.toPrimitives(arrayByte);
        return bytes;
    }

Error Log

03-13 11:56:27.480: E/AndroidRuntime(10471): Caused by: java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.Byte[]
Jon Skeet
people
quotationmark

Your toArray call needs to tell the list what kind of array to create:

Byte[] arrayByte = super.toArray(new Byte[size()]);

That can't otherwise be inferred at execution time, due to type erasure - the list doesn't "know" that it's a List<Byte>.

Now because you're using a method with a declaration of:

<T> T[] toArray(T[] a)

you don't need to cast the result.

Note that you don't have to create an array of the right size - the method will create a new one if it needs to - but specifying the right size to start with avoids creating one array pointlessly, so it's slightly more efficient.

people

See more on this question at Stackoverflow