简体   繁体   中英

Add each element in array to a list

What's the easiest way add all of the elements in an array to a list?

eg

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.asList won't work because you've got a byte[] rather than a Byte[] .

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:

List<Byte> l = new ArrayList<Byte>();
for (byte b : "something".getBytes("UTF-8"))
{
    l.add(b);
}

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 Byte objects, you're still going to have 4 or 8 bytes per element, as they'll be references. It's very rare for a List<Byte> to be appropriate - are you sure you need it here?

If you're actually dealing with classes, eg you've got a String[] and you want a List<String> then you can use Arrays.asList() :

String[] array = ...;
List<String> list = Arrays.asList(array);

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 ArrayList constructor:

String[] array = ...;
List<String> list = new ArrayList<String>(Arrays.asList(array));

Unless you want to add every element one at a time in a loop, you can use Apache commons' ArrayUtils to convert the primitive array into an Object array, then use addAll() :

byte[] b = "something".getBytes("UTF-8");
Byte[] bArray = ArrayUtils.toObject(b);

List<Byte> l = new ArrayList<Byte>();
l.addAll(bArray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM