Java List generics syntax for primitive types
I want to make a growable array of bytes开发者_如何学JAVA. I.e a list. In c# would usally do the following syntax
List<byte> mylist = new List<byte>();
where as in java this syntax does not work and I have googled around and found the below code
List myList = new ArrayList();
but that is not what I want. Any idea's where I am going wrong?
You could also use TByteArrayList from the GNU Trove library.
Use the wrapper class Byte
:
List<Byte> mylist = new ArrayList<Byte>();
Then, because of autoboxing, you can still have:
for (byte b : mylist) {
}
You have a Byte
class provided by the JRE.
This class is the corresponding class for the byte
primitive type.
See here for primitive types.
You can do this :
List<Byte> myList = new ArrayList<Byte>();
byte b = 127;
myList.add(b);
b = 0; // resetting
b = myList.get(0); // => b = 127 again
As Michael pointed in the comments :
List<Byte> myList = new ArrayList<Byte>();
Byte b = null;
myList.add(b);
byte primitiveByte = myList.get(0);
results in :
Exception in thread "main" java.lang.NullPointerException
at TestPrimitive.main(TestPrimitive.java:12)
Note that using an ArrayList<Byte>
to store a growable array of bytes is probably not a good idea, since each byte gets boxed, which means a new Byte object is allocated. So the total memory cost per byte is one pointer in the ArrayList + one Byte object.
It's probably better to use a java.io.ByteArrayOutputStream
. There, the memory cost per byte is 1 byte.
We can provide better advice if you describe the context a little more.
精彩评论