Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer

前端 未结 5 1544
[愿得一人]
[愿得一人] 2020-12-29 17:06

I have written a generic class and below is the constructor of the class. I want to do something like this as written in line

elements = (E[])new Object[siz         


        
5条回答
  •  伪装坚强ぢ
    2020-12-29 17:38

    Here is the most-minimal code necessary to reproduce your exception.

    class Stack {
        protected E[] elements = (E[])new Object[1];
    }
    
    class IntStack extends Stack {
        void push(Integer i) {
            // subtly accessing elements as Integer[] which it's not
            elements[0] = i;
        }
    }
    

    Java generics are implemented with type erasure so after compilation, this code translates to something like this:

    class Stack {
        protected Object[] elements = new Object[1];
    }
    
    class IntStack extends Stack {
        void push(Integer i) {
            // throws ClassCastException
            ((Integer[])elements)[0] = i;
        }
    }
    

    Clearly a new Object[] is not an Integer[]. Notice how the cast gets moved to somewhere you did not explicitly put it. This is why (E[])new Object[size] was an unchecked cast and displayed a warning.

    Instead, you should use Object[] and perform the unchecked cast only when you need to return an element to the outside world.

    class Stack {
        private Object[] elements;
        private int size;
    
        Stack(int len) {
            elements = new Object[len];
        }
    
        void push(E e) {
            elements[size] = e;
            size++;
        }
    
        E pop() {
           @SuppressWarnings("unchecked");
           E e = (E)elements[size - 1];
           size--;
           return e;
        }
    }
    

提交回复
热议问题