Returns a byte array containing the bytes from the List. - Java java.lang

Java examples for java.lang:byte Array

Description

Returns a byte array containing the bytes from the List.

Demo Code


//package com.java2s;

import java.util.List;

public class Main {
    public static void main(String[] argv) throws Exception {
        List data = java.util.Arrays.asList("asdf", "java2s.com");
        System.out.println(java.util.Arrays
                .toString(getByteArrayFromList(data)));
    }/*from  w  w  w  .j a  va2s .co m*/

    /**
     * Returns a byte array containing the bytes from the <code>List</code>.
     * The <code>List</code> must contain <code>Byte</code> objects.
     * <code>null</code> entries in the <code>List</code> are
     * allowed, the resulting byte will be 0.
     * @param data the <code>List</code>
     * @return the resulting byte array
     */
    public static byte[] getByteArrayFromList(List data) {
        return getByteArrayFromList(data, 0);
    }

    /**
     * Returns a byte array containing the bytes from the <code>List</code>.
     * The <code>List</code> must contain <code>Byte</code> objects.
     * <code>null</code> entries in the <code>List</code> are
     * allowed, the resulting byte will be 0.
     * @param data the <code>List</code>
     * @param index the index at which to start
     * @return the resulting byte array
     */
    public static byte[] getByteArrayFromList(List data, int index) {
        return getByteArrayFromList(data, index, data.size() - index);
    }

    /**
     * Returns a byte array containing the bytes from the <code>List</code>.
     * The <code>List</code> must contain <code>Byte</code> objects.
     * <code>null</code> entries in the <code>List</code> are
     * allowed, the resulting byte will be 0.
     * @param data the <code>List</code>
     * @param index the index at which to start
     * @param len the number of bytes
     * @return the resulting byte array
     */
    public static byte[] getByteArrayFromList(List data, int index, int len) {
        if (data.size() == 0)
            return new byte[0];
        if (index >= data.size()) {
            throw new IndexOutOfBoundsException("Position " + index
                    + " invalid in List of size " + data.size());
        }
        byte[] byteData = new byte[len];
        for (int ii = index; ii < data.size() && ii < index + len; ii++) {
            Byte nextValue = (Byte) data.get(ii);
            if (null != nextValue) {
                byteData[ii - index] = nextValue.byteValue();
            }
        }
        return byteData;
    }
}

Related Tutorials