开发者

Get byte[] from List<Byte> [duplicate]

This question already has answers here: Closed 12 years ago.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜