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? Commented 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.... Commented May 1, 2016 at 15:39
  • 2
    stackoverflow.com/questions/14524751/… Commented May 1, 2016 at 15:42

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]; 
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

This is where I'm at right now, how can I deal with the "unchecked cast" warning?
You can always supress it with @SuppressWarnings("unchecked"). Take a look at this thread: stackoverflow.com/questions/509076/…
When instantiating my array above my function like so: T arr[], would I have to instantiate it as a T type, or Object type?
Interesting way of waiting for a RuntimeException, when T gets a bound.
@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/…
-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() }

Comments

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.