How to convert byte[] to Byte[] and the other way around?
Byte
class is a wrapper for the primitive byte
. This should do the work:
byte[] bytes = new byte[10];Byte[] byteObjects = new Byte[bytes.length];int i=0; // Associating Byte array values with bytes. (byte[] to Byte[])for(byte b: bytes) byteObjects[i++] = b; // Autoboxing.....int j=0;// Unboxing Byte values. (Byte[] to byte[])for(Byte b: byteObjects) bytes[j++] = b.byteValue();
Java 8 solution:
Byte[] toObjects(byte[] bytesPrim) { Byte[] bytes = new Byte[bytesPrim.length]; Arrays.setAll(bytes, n -> bytesPrim[n]); return bytes;}
Unfortunately, you can't do this to convert from Byte[]
to byte[]
. Arrays
has setAll
for double[]
, int[]
, and long[]
, but not for other primitive types.