Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: byte[] to Byte[]

Java makes me sad since it needs wrapper classes for ArrayLists. How would I go about adding a byte[] to a ArrayList<Byte[]>?

like image 841
CSharpLover Avatar asked Feb 11 '10 21:02

CSharpLover


People also ask

What is byte [] in Java?

A byte in Java is 8 bits. It is a primitive data type, meaning it comes packaged with Java. Bytes can hold values from -128 to 127. No special tasks are needed to use it; simply declare a byte variable and you are off to the races.

How do I combine byte arrays?

The recommended solution to concatenate two or more byte arrays is using ByteArrayOutputStream . The idea is to write bytes from each of the byte arrays to the output stream, and then call toByteArray() to get the current contents of the output stream as a byte array.

How do you convert Bytearray to long?

Similarly, the BigInteger class has a longValue() method to convert a byte array to a long value: long value = new BigInteger(bytes). longValue();

How do you assign a byte array in Java?

Arrays. fill(). This method assigns the required byte value to the byte array in Java.


4 Answers

LOL thought I had to wrap everything. ArrayList<byte[]> works. Thanks Yishai.

like image 79
CSharpLover Avatar answered Nov 14 '22 23:11

CSharpLover


You have to wrap any primitives to use them in a context that requires an object. But a byte[] is not a primitive. It's an array of bytes, and an array is an object.

Just to clarify: Do you really want an ArrayList of arrays of bytes, i.e. effectively a two-dimensional array? Or do you really simply want an ArrayList of bytes? In that case, you would have to wrap the bytes in Bytes to put them in the ArrayList.

like image 36
Jay Avatar answered Nov 14 '22 23:11

Jay


Just for the purpose of others searching for this, if you have Apache Commons on your classpath, you can do something like the following to get Byte[] back (documentation]:

Byte[] result = ArrayUtils.toObject(byte[]);
like image 32
Daan Gerits Avatar answered Nov 14 '22 22:11

Daan Gerits


ArrayList works only, if you do not require the results of hashCode() and equals() on this list.

like image 34
Aison Avatar answered Nov 14 '22 23:11

Aison