2011-02-01 50 views
0

可能重复:
Creating a byte[] from a List<Byte>获取的byte []从列表<Byte>

我有名单列表。如何从startIndex到endIndex id列表中获取byte [](列表的子列表)?

+1

你是指Byte []还是byte []? – Joel 2011-02-01 11:28:25

+0

@Joel我不认为这是重复的。这个问题只是关于将字节[]转换为字节[] ...这一个是关于(列表到数组)+子列表 – 2011-02-01 12:02:39

回答

2
List<Byte> theList= new ArrayList<Byte>(); 
Byte[] your_bytes = theList.subList(startIndex,endIndex).toArray(new Byte[0]); 

如果最后你需要byte(原始)工作的话,我建议的Apache Commons Collections中toPrimitive utility

byte[] your_primitive_bytes = ArrayUtils.toPrimitive(your_bytes); 

在大多数情况下,你当然可以用Byte(对象)度日。

0
ArrayList<Byte> list = new ArrayList<Byte>(); 

ArrayList<Byte> subList = (ArrayList<Byte>) list.subList(fromIndex, toIndex); //(0,5) 

Byte[] array = (Byte[]) subList.toArray(); 
0

好了,因为原来的问题实际上请求包含一个字节一个子表[](不是字节[])这里有云:

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(); 
    } 
0

如果您需要byte[]

byte[] byteArray = ArrayUtils.toPrimitive(list.subList(startIndex, endIndex).toArray(new Byte[0])); 

ArrayUtils.toPrimitive