Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
670 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...