40

Trying to solve what should be a simple problem. Got a list of Bytes, want to convert it at the end of a function to an array of bytes.

final List<Byte> pdu = new ArrayList<Byte>();
....
return pdu.toArray(new byte[pdu.size()]);;

compiler doesn't like syntax on my toArray. How to fix this?

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
fred basset
  • 9,774
  • 28
  • 88
  • 138

4 Answers4

57

The compiler doesn't like it, because byte[] isn't Byte[].

What you can do is use commons-lang's ArrayUtils.toPrimitive(wrapperCollection):

Byte[] bytes = pdu.toArray(new Byte[pdu.size()]);
return ArrayUtils.toPrimitive(bytes);

If you can't use commons-lang, simply loop through the array and fill another array of type byte[] with the values (they will be automatically unboxed)

If you can live with Byte[] instead of byte[] - leave it that way.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
31

Use Guava's method Bytes.toArray(Collection<Byte> collection).

List<Byte> list = ...
byte[] bytes = Bytes.toArray(list);

This saves you having to do the intermediate array conversion that the Commons Lang equivalent requires yourself.

ColinD
  • 108,630
  • 30
  • 201
  • 202
5

Mainly, you cannot use a primitive type with toArray(T[]).

See: How to convert List<Integer> to int[] in Java?. This is the same problem applied to integers.

Community
  • 1
  • 1
Kru
  • 4,195
  • 24
  • 31
1

try also Dollar (check this revision):

import static com.humaorie.dollar.Dollar.*
...

List<Byte> pdu = ...;
byte[] bytes = $(pdu).convert().toByteArray();
dfa
  • 114,442
  • 31
  • 189
  • 228