1

I'm getting this odd error in my Java and I'm completely stuck.

private List<byte[]> sharedWorlds = Collections.synchronizedList(new ArrayList<byte[]>());

Byte[] y = sharedWorlds.toArray(new Byte[0]);

try{

    //this line won't compile!
    Utilities.writeByteArray(outStream, sharedWorlds.toArray(new Byte[0]));

}catch(Exception e){
    System.out.println("Error!");
}

Type mismatch: cannot convert from Byte[] to byte[]

The second parameter to "writeByteArray" needs to be a byte[] and not a Byte[]...

I could loop through a new byte[] and copy every element, but this seems unclean and inefficient?

I tried casting

(byte[]) sharedWorlds.toArray(new Byte[0])

but this errors with

Cannot cast from Byte[] to byte[]

My Java is rusty, but I have no idea what's going on here.

5
  • 1
    @GalAbra: It's not really a duplicate of that IMO, as byte is a primitive type... it's a slightly different situation. Commented Mar 3, 2018 at 11:28
  • 1
    What's unclear to me is why you're creating a Byte[] at all. Why not do everything using byte[]? Commented Mar 3, 2018 at 11:29
  • 2
    My apologies, but try looking into this Commented Mar 3, 2018 at 11:30
  • @Jon Skeet. I tried but I couldn't do it ;( the "sharedWorlds" object is of type List<byte[]> sharedWorlds Commented Mar 3, 2018 at 11:35
  • Then show what you've tried, using byte[] everywhere, and the error. Commented Mar 3, 2018 at 11:39

1 Answer 1

0

It appears from some quick research that direct conversion isn't supported in Java.

You can use Apache Commons Lang ArrayUtils.toPrimitive() http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/ArrayUtils.html#toPrimitive(java.lang.Integer[])

Or you can use a for loop to copy an object Byte array to a primitive byte array.

More info and example here Converting an array of objects to an array of their primitive types

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

3 Comments

From looking at @GalAbra's link, I ended up using Apache Commons Lang ArrayUtils i.e. Utilities.writeByteArray(outStream, ArrayUtils.toPrimitive(sharedWorlds.toArray(new Byte[0])));
Why don't you just vote to close as duplicate?
Good point, I will delete my answer and vote to close as duplicate

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.