Get byte[] from List<Byte> [duplicate]
Possible Duplicate:
Creating a byte[] from a List<Byte>
I have List list. How to get byte[] ( subarray of list ) from startIndex开发者_JAVA技巧 to endIndex id list ?
List<Byte> theList= new ArrayList<Byte>();
Byte[] your_bytes = theList.subList(startIndex,endIndex).toArray(new Byte[0]);
If finally you need to work with byte
(the primitive) then I recommend Apache Commons Collections toPrimitive utility
byte[] your_primitive_bytes = ArrayUtils.toPrimitive(your_bytes);
For most cases you certainly can get by with Byte
(object).
ArrayList<Byte> list = new ArrayList<Byte>();
ArrayList<Byte> subList = (ArrayList<Byte>) list.subList(fromIndex, toIndex); //(0,5)
Byte[] array = (Byte[]) subList.toArray();
Well, since the original question actually asks for a sublist containing a byte[] (not Byte[]) here goes:
List<Byte> byteList = .... some pre-populated list
int start = 5;
int end = 10;
byte[] bytes = new byte[end-start]; // OP explicitly asks for byte[] (unless it's a typo)
for (int i = start; i < end; i++) {
bytes[i-start] = byteList.get(i).byteValue();
}
If you need byte[]
:
byte[] byteArray = ArrayUtils.toPrimitive(list.subList(startIndex, endIndex).toArray(new Byte[0]));
ArrayUtils.toPrimitive
精彩评论