开发者

create array from parameter in java

开发者 https://www.devze.com 2023-03-16 16:38 出处:网络
I have implemented array list with arrays: public class ArrayIndexList<E> { private E[] A; private int capacity = 5; // Initial Array Size

I have implemented array list with arrays:

public class ArrayIndexList<E> {
    private E[] A;
    private int capacity = 5; // Initial Array Size
    private int size = 0;

    public ArrayIndexList() {
        A = (E[]) new Object[capacity];
    }

    public void add(int index, E element) {
        /* if array is full:
         * 1. double the array size
         * 2. copy elements to the new array */
        if (size == capacity) {
            capacity = capacity * 2;
            E[] B = (E[]) new Object[capacity];
            for 开发者_开发百科(int i = 0;i < size;i++)
            B[i] = A[i];
            A = B;
        }

        // shift the elements up
        for (int i = size - 1;i >= index;i--)
            A[i + 1] = A[i];

        // add new element
        A[index] = element;
        size = size + 1;
    }

    public E remove(int index) {
        E temp = A[index];

        //shift elements down
        for (int i = index;i < size - 1;i++)
            A[i] = A[i + 1];
        size = size - 1;

        return temp;
    }
}

It is working, but compiler gives warning:

Type safety: Unchecked cast from Object[] to E[] ArrayIndexList.java

What's wrong with the code?


The cast cannot be checked a runtime, therefore a warning is given. With an up to date compiler, you can suppress the warning using @SuppressWarnings("unchecked").

was it helpful ?

http://mindprod.com/jgloss/compileerrormessages.html#TYPESAFETYERASED


You are actually kind of lying when you cast from Object[] to E[], because arrays hold their component type at runtime, so it is not possible in reality to cast from Object[] to a more specific array type; but since you are within the type parameter E's scope, E[] is erased so that does not cause an error.

This is actually the best you can do, because the only other alternative is to have the variable "A" be of type Object[], but then you would have to cast into E every time you get something out of it, which would generate even more unchecked cast warnings. There is no way you can get out of it, so you just have to suppress them. (unless you wrap a pre-made type that does what your class does like ArrayList, which itself does the same thing and has to suppress these warnings internally)

0

精彩评论

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

关注公众号