0

I have a generic class, SimpleStack<T>, which contains these methods:

private T[] stack;

public T[] getStack() {
    return this.stack;
}

public boolean add(T item) {
    boolean filled = isFull();
    if (!filled) {
        stack[size()] = item;
        return true;
    }
    else {
        return false;
    }
}

public int size() {
    int count = 0;
    for (T item : stack) {
        if (item != null) {
            count++;
        }
    }
    return count;
}

I'm trying to use this class to act as a Profile class, and I've filled the array stack with Profile objects. However, when I try to return this array, it says that it can't cast from Object to Profile.

Here's a snippet from where I fill the array, inside my main method:

SimpleStack<Profile> profiles = new SimpleStack<Profile>(50);
Profile profile = new Profile();
profiles.add(profile);

I try to call the getter to return the array, and cast it to a Profile[]. This is what fails:

Profile[] tempStack = Arrays.copyOf(profiles.getStack(), (profiles.getStack()).length, Profile[].class);

I've tried it several ways, but the ultimately all do the same thing (attempt to cast the generic array to Profile[]).

Does anyone know what I've done wrong? I can provide more code if necessary. I tried to take the relevant bits.

MC Emperor
  • 17,266
  • 13
  • 70
  • 106
Cory
  • 33
  • 12

2 Answers2

0

It all depends how you initialize it. See How to create a generic array in Java? for more details.

public class SimpleStack<T> {
    private final T[] stack;

    public SimpleStack(Class<T[]> clazz, int size) {
        this.stack = clazz.cast(Array.newInstance(clazz.getComponentType(), size));
    }

    public T[] getStack() {
        return stack;
    }

    public static void main(String... args) {
        SimpleStack<Profile> profiles = new SimpleStack<>(Profile[].class, 50);
        Profile profile = new Profile();
        Profile[] array = profiles.getStack();
    }

    public static class Profile {

    }
}

Note that I prefer to use clazz.cast() instead of a dirty cast, because it is safer and you don't have to use @SuppressWarnings

Amir Raminfar
  • 32,592
  • 7
  • 83
  • 119
0

This, stack = (T[]) new Object[size]; isn't allowed. Because of type-erasure, the type T is Object at run-time. However, you can pass in the class type to your generic class, that will allow you to use Array.newInstance(Class, int).

static <E> E[] makeAnArray(Class<E> cls, int length) {
    return (E[]) Array.newInstance(cls, length);
}
Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226