Default constructor issue when creating an array Java

此生再无相见时 提交于 2019-12-13 23:18:02

问题


I have the following class:

public class ArrayObjects<E> implements SomeImp<E>{
    int maxCapacity, actualSize;

    public ArrayObjects(){
        maxCapacity = 10;
        array = (E[]) new Object[maxCapacity];
    }
}

Eclipse marks an error and says the following:

"array cannot be resolved to a variable"

Also it shows some additional details:

-Type safety: Unchecked cast from Object[] to E[]

Does anyone know what am I doing wrong? My goal is to have an array in my class constructor that can hold any kind of object (that's why I am trying to make it generic) but apparently this approach will not work.

Thank you for your help!!


回答1:


The error message tells you exactly what's wrong. There is no declared variable by the name of array.

public class ArrayObjects<E> implements SomeImp<E> {
    int maxCapacity, actualSize;
    E[] array; // <- The missing declaration

    @SuppressWarnings("unchecked") // <- Suppress the "unchecked cast" warning
    public ArrayObjects() {
        maxCapacity = 10;
        array = (E[]) new Object[maxCapacity];
    }
}

As far as the unchecked cast goes, the best thing you can do there is to suppress it as shown above.



来源:https://stackoverflow.com/questions/28597396/default-constructor-issue-when-creating-an-array-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!