4

Both can be used to create an list of bytes. But what is the difference between them?

byte[] buffer;
List<Byte> buffer;
Machado
  • 14,105
  • 13
  • 56
  • 97

3 Answers3

10

Both can be used to create an array of bytes

No, the first one creates an array of bytes. The second one defines a list of bytes, which may or may not be backed by an array depending on which List implementation you use.

An array is fixed-size and pre-allocated; if you need to grow the array, you need to create a new, larger array, copy the contents over, and then add the new contents.

Lists, on the other hand, are generally dynamic, growing as you add things to them, shrinking as you remove things from them, etc. One list implementation, ArrayList, does this by maintaining a backing array, usually with some slack in it, and then doing the reallocation-and-copy as necessary when you add to it.

Also note that List can't actually contain primitive byte values; instead, it'll contain Byte objects (via a process called autoboxing).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • is there anyway to convert a List object into a byte[] array? – Machado Jan 26 '15 at 12:47
  • 1
    @Tardo Sure. 1) create a `byte[]` with the size of the list; 2) traverse the list; 3) for each `Byte` in the list, insert its primitive value into the array. – afsantos Jan 26 '15 at 12:50
  • 1
    @Tardo: Well, there's that tempting [`List#toArray(T[] a)`](http://docs.oracle.com/javase/8/docs/api/java/util/List.html#toArray-T:A-) method on the `List` interface. I've never used it to auto-unbox `List` to `byte[]`, don't know whether that would be automatic. – T.J. Crowder Jan 26 '15 at 12:50
  • 1
    @Tardo: Just tried it, and no, you can't use `List#toArray(T[] a)` unless I was doing it wrong (you can get `Byte[]`, but not `byte[]`). So as afsantos said, you'd have to do it with a loop. – T.J. Crowder Jan 26 '15 at 12:53
4
  • The byte[] array has a fixed size, while the list doesn't.
  • The byte[] array contains primitive byte values, while the list contains boxed ones, therefore the list will need more memory

More info:

Community
  • 1
  • 1
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
2

byte[] buffer is a premitive array of premetive byte without any methods that can be made either on the Byte and either in the []
List<Byte> buffer is List object of Byte object which also have methods on it which defined in Byte

roeygol
  • 4,908
  • 9
  • 51
  • 88