PlanetXML

List Wrapper für Arrays primitiver Datentypen

Diese Klasse ist ein Wrapper für Arrays Primitiver Datentypen. Der Zugriff auf einzelne Elemente geschieht dabei über Reflection. Die Funktionalität entspricht ansonsten der Methode java.util.Arrays.asList.

import java.io.Serializable;

import java.lang.reflect.Array;

import java.util.AbstractList;
import java.util.RandomAccess;

public class PrimitiveList extends AbstractList implements RandomAccess, Serializable {
    private static final long serialVersionUID = 165651237L;
    private Object array = null;

    private void init(Object array) {
        if (array==null)
            throw new NullPointerException();
        this.array = array;
    }

    public PrimitiveList(boolean[] array) {
        init(array);
    }

    public PrimitiveList(byte[] array) {
        init(array);
    }

    public PrimitiveList(short[] array) {
        init(array);
    }

    public PrimitiveList(char[] array) {
        init(array);
    }

    public PrimitiveList(int[] array) {
        init(array);
    }

    public PrimitiveList(long[] array) {
        init(array);
    }

    public PrimitiveList(float[] array) {
        init(array);
    }

    public PrimitiveList(double[] array) {
        init(array);
    }

    public int size() {
        return Array.getLength(array);
    }

    public Object get(int index) {
        return Array.get(array, index);
    }

    public Object set(int index, Object value) {
        Object oldValue = Array.get(array, index);
        Array.set(array, index, value);
        return oldValue;
    }

    public int indexOf(Object o) {
        if (o == null) {
            throw new NullPointerException();
        }

        int len = Array.getLength(array);
        for (int i=0; i<len; i++) {
            if (o.equals(Array.get(array, i))) {
                return i;
            }
        }
        return -1;
    }

    public boolean contains(Object o) {
        return indexOf(o) != -1;
    }

    /**
     * Testcode.public
     */
    public static void main(String[] args) {
        System.out.println(new PrimitiveList(new boolean[] {true,false,false}));
        System.out.println(new PrimitiveList(new byte[] {1,3,2}));
        System.out.println(new PrimitiveList(new short[] {1,3,2}));
        System.out.println(new PrimitiveList(new char[] {'a', 'b', 'c'}));
        System.out.println(new PrimitiveList(new int[] {1,3,2}));
        System.out.println(new PrimitiveList(new long[] {1,3,2}));
        System.out.println(new PrimitiveList(new float[] {1.1f,3.3f,2.2f}));
        System.out.println(new PrimitiveList(new double[] {1.1,3.3,2.2}));

        System.out.println(new PrimitiveList(new int[] {1,3,2}).indexOf(new Integer(2)));
        System.out.println(new PrimitiveList(new int[] {1,3,2}).indexOf(new Integer(3)));

        System.out.println(new PrimitiveList(new int[] {1,3,2}).set(2, new Integer(3)));
    }
}