-4

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

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your response! Another kind of beginner question. What's the difference if I put public in front of my int/ E[ ] declarations? Thanks again
@JTarantino public means the variable is visible from other classes
Here is a good resource that describes access modifiers in Java: docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.