0

I was trying to create a new data type with generics but the javac compiler keeps telling me

"Note: MyStack.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
, when I try to recompile it with the option -Xlint, 
"MyStack.java:8: warning: [unchecked] unchecked cast
        data = (T[]) new Object[5];
                 ^
  required: T[]
  found:    Object[]
  where T is a type-variable:
    T extends Object declared in class MyStack
1 warning

. What should I do to avoid this warning?

public class MyStack<T> {

    int index;
    private T[] data;

    public MyStack() {
        index = 0;
        data = (T[]) new Object[5];
    }

    public void push(T input) {
        data[index++] = input;
    }

    public T pop() {
        return data[--index];
    }

}
sh.seo
  • 1,482
  • 13
  • 20
Ah Lag
  • 91
  • 1
  • 12

2 Answers2

0

I think there is not way to avoid warning. In this ask we can see a solution using Array.newInstance(class, size). But we should add annotation '@SuppressWarnings("unchecked")' to deal with it.

Also, if you are not do programming exercise or do a framework / library. I recommend you to use the java.collection data structures.

I Hope I helped you

0

An array has a distinct type at runtime. If you create an array of Object, that is its permanent runtime type:

Object[] data = new Object[5];
System.out.println(data.getClass());    // Prints class [Ljava.lang.Object;
  • If you create an array of String, the array’s permanent runtime type is [Ljava.lang.String;.
  • If you create an array of int, the array’s permanent runtime type is [I.

And so on.

Generic types do not exist at runtime. They are a type safety mechanism enforced entirely by the compiler. This means there is no T at runtime, which means it is not possible to compile T[] because the compiler cannot generate code that creates a specific, known array type.

What can you do about it? Normally, you would use a Collection class, like ArrayList, but I’m guessing your assignment doesn’t allow that.

One way to enforce generics at runtime is by keeping a Class object in each MyStack instance.

public class MyStack<T> {

    int index;
    private Object[] data;
    private final Class<T> elementType;

    public MyStack(Class<T> elementType) {
        this.elementType = elementType;
        index = 0;
        data = new Object[5];
    }

You can then use the cast method to provide type safety in the pop method:

public T pop() {
    return elementType.cast(data[--index]);
}
VGR
  • 40,506
  • 4
  • 48
  • 63