"cannot convert from Byte[] to byte[]"?

ArrayList<Byte> byteList;
...(inserting data into bytelist)...
byte[] data = byteList.toArray(new Byte[c1.byteList.size()]);

So basically I'm manipulating byte data in an array list, because it's easier to add or delete this way, then after manipulating data I tried to convert byte arraylist back to byte array...well that's the point when porcessing gives me the "cannot convert from Byte[] to byte[]" error. Anyone have any idea on this? Please help!

Tagged:

Answers

  • edited October 2013

    You provide the wrong type to toArray...

    Beside, auto-unboxing doesn't work automatically on arrays. I fear you have to loop on the array list manually to fill your array.

  • Answer ✓
    ArrayList<Byte> byteList = new ArrayList<Byte>();
    byteList.add((byte) 5); // Auto-boxing
    byteList.add((byte) 15);
    byte[] data = new byte[byteList.size()];
    for (int i = 0; i < data.length; i++)
    {
      data[i] = byteList.get(i); // Auto-unboxing
    }
    println(data);
    
  • edited November 2013 Answer ✓

    Most direct inline conversion possible (as you already noticed) is to a Byte[]; which is a byte class wrapper type: :-@

    // forum.processing.org/two/discussion/777/cannot-convert-from-byte-to-byte
    
    final ArrayList<Byte> byteList = new ArrayList();
    
    byteList.add((byte) 5.5);
    byteList.add((byte) 'a');
    byteList.add((byte) -25);
    
    println(byteList);
    println();
    
    final Byte[] wrapperByteArray = byteList.toArray( new Byte[byteList.size()] );
    
    println(wrapperByteArray);
    
    exit();
    

    And as PhiLho already demonstrated, to get a real byte[], we gotta copy each element to the other: 8-|

    // forum.processing.org/two/discussion/777/cannot-convert-from-byte-to-byte
    
    final ArrayList<Byte> byteList = new ArrayList();
    
    byteList.add((byte) 5.5);
    byteList.add((byte) 'a');
    byteList.add((byte) -25);
    
    println(byteList);
    println();
    
    final byte[] byteArray = new byte[byteList.size()];
    
    int i = 0;
    for (byte b: byteList)   byteArray[i++] = b;
    
    println(byteArray);
    
    exit();
    
  • Thanks so much guys!

Sign In or Register to comment.