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.

Eamorr
  • 9,872
  • 34
  • 125
  • 209
  • 1
    @GalAbra: It's not really a duplicate of that IMO, as `byte` is a primitive type... it's a slightly different situation. – Jon Skeet Mar 03 '18 at 11:28
  • 1
    What's unclear to me is why you're creating a `Byte[]` at all. Why not do everything using `byte[]`? – Jon Skeet Mar 03 '18 at 11:29
  • 2
    My apologies, but try looking into [this](https://stackoverflow.com/questions/564392/converting-an-array-of-objects-to-an-array-of-their-primitive-types) – GalAbra Mar 03 '18 at 11:30
  • @Jon Skeet. I tried but I couldn't do it ;( the "sharedWorlds" object is of type `List sharedWorlds` – Eamorr Mar 03 '18 at 11:35
  • Then show what you've tried, using `byte[]` everywhere, and the error. – Jon Skeet Mar 03 '18 at 11:39

1 Answers1

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

BateTech
  • 5,780
  • 3
  • 20
  • 31