0

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[]
0

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.