What’s the easiest way add all of the elements in an array to a list?
e.g.
List<Byte> l = new ArrayList<Byte>();
//Want to add each element in below array to l
byte[] b = "something".getBytes("UTF-8");
Is there some utility method or something that does this. I tried to use addAll, but that wants to add the actual array to the collection.
Thank you.
EDIT:
To clarify, I do want to do this with byte[] because I am going to eventually convert the list back to a byte[] and feed it into MessageDigest.update(). Does that help clarify?
EDIT 2:
So it seems like List<Byte> is bad; very bad. What data structure would be recommended if I am basically adding arrays of bytes (I am making a hash of some some SALTS and user information) to feed into MessageDigest?
For
byte[], you’re in trouble.Arrays.asListwon’t work because you’ve got abyte[]rather than aByte[].This is one of those “primitive vs class” problems. You can probably find 3rd party collection libraries which support this (such as the Apache Commons Lang project), but I don’t believe there’s anything out of the box. Alternatively, you could always just write the code yourself:
Note that this is a pretty horribly inefficient storage format for a sequence of bytes. Even though autoboxing will ensure you don’t create any extra
Byteobjects, you’re still going to have 4 or 8 bytes per element, as they’ll be references. It’s very rare for aList<Byte>to be appropriate – are you sure you need it here?If you’re actually dealing with classes, e.g. you’ve got a
String[]and you want aList<String>then you can useArrays.asList():That will return a read-only list wrapping the array though – if you want a mutable list, you can just pass that wrapper to the
ArrayListconstructor: