问题
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