Machado
Machado

Reputation: 14489

What is the difference between byte[] and List<Byte> in Java?

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

byte[] buffer;
List<Byte> buffer;

Upvotes: 4

Views: 4365

Answers (3)

roeygol
roeygol

Reputation: 5028

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

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074238

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).

Upvotes: 10

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

  • 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:

Upvotes: 4

Related Questions