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

前端 未结 5 1559
[愿得一人]
[愿得一人] 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:55

    Here is how you would fix it, you should not ever do (T[]) new Object[DEFAULT_CAPACITY]; instead an abstraction should be there for example (T[]) new Comparable[DEFAULT_CAPACITY];

    public class ArrayStack> implements Stack {
    
    private final int DEFAULT_CAPACITY = 50;
    
    private int top;
    private T[] elements;
    
    @SuppressWarnings("unchecked")
    public ArrayStack() {
        this.elements   = (T[]) new Comparable[DEFAULT_CAPACITY];
        this.top        = 0;
    }
    }
    

提交回复
热议问题