0

I am creating a stack of generic type that is backed by an array. When I try to make a generic type array, Java does not let me. I've been told that I must create an array of type Object and cast it to a generic type. I've casted my Object array to type , but how can I deal with the Unchecked Type error that Java keeps giving me?

public class AStack<T>{
// Create a stack with the default capacity 10. The stack expands
// its internal array when the number of elements pushed() into it
// would exceed the internal capacity.

Object arr[];
int top=-1;

public AStack(){
int defSize=10;
arr = (T[])new Object [defSize]; 
}

This is where I am so far.

UPDATE: I am creating an Object array, then casting the return types to type T at the end of the method.

3
  • I don't see a problem with how i've done it, what's wrong?
    – ChrisAngj
    May 1, 2016 at 15:38
  • 1
    You could do something like this : Create a generic AStack class like this class AStack<E> .... declare the array like E[] arr = (E[])new Object[size]; -> this will generate a warning but you can ignore this as during type erasure of E, you will anyway be left with an Object array....now your methods can all assume that the array is of type E and work without casts.... May 1, 2016 at 15:39
  • 2

2 Answers 2

6

The simplest way is to use the type variable to cast array of objects to desired type.

public class AStack<T> {
    T arr[];
    int top=-1;

    public AStack() {
        int defSize=10;
        arr = (T[]) new Object [defSize]; 
    }
}
5
  • This is where I'm at right now, how can I deal with the "unchecked cast" warning?
    – ChrisAngj
    May 1, 2016 at 15:54
  • 1
    You can always supress it with @SuppressWarnings("unchecked"). Take a look at this thread: stackoverflow.com/questions/509076/… May 1, 2016 at 16:03
  • When instantiating my array above my function like so: T arr[], would I have to instantiate it as a T type, or Object type?
    – ChrisAngj
    May 1, 2016 at 16:14
  • Interesting way of waiting for a RuntimeException, when T gets a bound.
    – Tom
    May 1, 2016 at 16:24
  • 1
    @ChrisAngj, the actual type of the created array is Object[]. Storing it in and accesing it by a typed array reference simply allows us not to do manual casts. It is safe as long asAStack is using this array internaly. See also: stackoverflow.com/questions/17831896/… May 1, 2016 at 21:05
-1

You could use an interface or a class that is extended to all the other classes you want to make generic and then use the interface or the class as the type of the array and now you could insert your specific types into the array.

GenericType[] array = { new specificType1(), new specificType2(), new specificType3() }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.