Java List Generator Syntax for Primitive Types

I want to create a massive array of bytes. I. list. In C #, the following syntax was usually performed

List<byte> mylist = new List<byte>(); 

where, as in java, this syntax does not work, and I encountered an error and found the code below

 List myList = new ArrayList(); 

but that’s not what I want. Any idea where I'm wrong?

+7
java collections list generics
source share
4 answers

Use the Byte wrapper class:

 List<Byte> mylist = new ArrayList<Byte>(); 

Then, due to autoboxing, you can still:

 for (byte b : mylist) { } 
+5
source share

You can also use the TByteArrayList from the GNU Trove library .

+6
source share

You have a Byte class provided by JRE.

This class is the corresponding class for the Byte primitive type.

See here for primitive types.

You can do it:

 List<Byte> myList = new ArrayList<Byte>(); byte b = 127; myList.add(b); b = 0; // resetting b = myList.get(0); // => b = 127 again 

As Michael noted in the comments:

 List<Byte> myList = new ArrayList<Byte>(); Byte b = null; myList.add(b); byte primitiveByte = myList.get(0); 

leads to:

 Exception in thread "main" java.lang.NullPointerException at TestPrimitive.main(TestPrimitive.java:12) 
+3
source share

Note that using an ArrayList<Byte> to store a growing array of bytes is probably not a good idea, as each byte receives a box, which means that a new Byte object is allocated. Thus, the total memory cost for each byte is one pointer in an ArrayList + one byte.

It is probably best to use java.io.ByteArrayOutputStream . There, the cost of memory per byte is 1 byte.

We can provide better advice if you describe the context in more detail.

0
source share

All Articles