Mehdi
Mehdi

Reputation: 2228

Create a List of byte[]

How might you go about creating a List of byte[] (not Byte)?

I want something like the following:

byte[] deb = new byte[Byte.MIN_VALUE];
List<byte[]> begin = new LinkedList<>();
begin.add(deb);

Upvotes: 0

Views: 385

Answers (5)

arshajii
arshajii

Reputation: 129497

That will work fine because arrays are objects in Java, so you can build Lists out of them.


Note that only in Java 7 can you do

List<byte[]> begin = new LinkedList<>();

In older versions you must restate the byte[]:

List<byte[]> begin = new LinkedList<byte[]>();

This has been brought up already but I'll just reiterate it here. Byte.MIN_VALUE is less than 0; you cannot create an array of length less than 0 (it results in a runtime error, specifically a NegativeArraySizeException). Did you mean Byte.MAX_VALUE?

Upvotes: 8

Amit Deshpande
Amit Deshpande

Reputation: 19185

Problem is at below line

 byte[] deb = new byte[Byte.MIN_VALUE]; <---Byte.MIN_VALUE -127 

You should declare your array with positive values Other wise you get NegativeArraySizeException.

byte[] deb = new byte[Some positive value];

Byte.MIN_VALUE is -127. You can not create negative index array in java.

Upvotes: 0

Gijs Overvliet
Gijs Overvliet

Reputation: 2691

First of all, Byte.MIN_VALUE is -128. If you try to create an array with negative length, you will get an error.

Second, as mentioned in other answers, the code to create the List should be

List<byte[]> begin = new LinkedList<byte[]>();

Upvotes: 0

anubhava
anubhava

Reputation: 784958

This should work fine:

List<byte[]> begin = new LinkedList<byte[]>();

Upvotes: 0

PermGenError
PermGenError

Reputation: 46398

Arrays in java are objects. byte[] is an array which holds byte values. collections accept objects, thus List is a collection which holds byte[]. your code should work without any problem.

Upvotes: 0

Related Questions