Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
675 views
in Technique[技术] by (71.8m points)

Default constructor issue when creating an array Java

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!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...