views:

180

answers:

4

I want to make a growable array of bytes. 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?

+4  A: 

Use the wrapper class Byte:

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

Then, because of autoboxing, you can still have:

for (byte b : mylist) {

}
Bozho
List is an interface, so you can't new one up. You'd need to use a concrete class instead, such as ArrayList or LinkedList
Michael Williamson
@Michael Williamson a typo, rather than me not knowing that ;)
Bozho
Thanks Bozho that worked for me.
Ciarán
+3  A: 

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)
subtenante
don't give links to 1.4.2
Bozho
It's probably worth adding that generics and primitives don't play nicely together -- that is, you can't use a primitive as a type argument, hence the need to use Byte instead of byte. Autoboxing isn't perfect -- a Byte can be null, where as a byte can't, so trying to assign a Byte to a byte can result in a null pointer exception.
Michael Williamson
@Bozho: They still show up as the first results on Google or Bing. One nice example where search engines suck ;-)
Joey
yes, they do. That's why I type "java.lang.Something 6"
Bozho
I always edit the URL (`j2se/1.4.2` => `javase/6`) before posting links to the docs.
finnw
A: 

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.

Bart Jacobs
A: 

You could also use TByteArrayList from the GNU Trove library.

finnw