Recompile with -Xlint:unchecked for detail error in java

Min Seok Song :

I have the following errors and I cannot seem to figure out how to debug it:

Note: MyStack.java uses unchecked or unsafe operations.

Note: Recompile with -Xlint:unchecked for details.

public class MyStack<T> implements MyStackInterface<T>{
        private T[] s;
        private int size;

    public MyStack() {
        this.s = (T[])new Object[30];
    }

    public void push(T x){
            if (size==s.length){
                T[] b = (T[])new Object[size*2];
                int i;
                for (i=0;i<s.length;i++){
                    b[i] = s[i];
                }
                s=b;
            }
            s[size++] = x;
        }
    public T pop(){
            if (size == 0){
                throw new RuntimeException("Stack Underflow");
            }
            return s[--size];
        }
    public T peek(){
            if (size==0) throw new RuntimeException("Stack Underflow");
            return s[size-1];
        }

    public boolean isEmpty(){
            return size==0;
        }
    public int size(){
            return size;
        }
}
Uriel Frankel :

When you compile the code use this:

javac -Xlint:unchecked

Then you will see:

MyStack.java:6: warning: [unchecked] unchecked cast
    this.s = (T[])new Object[30];
                  ^
  required: T[]
  found:    Object[]
  where T is a type-variable:
     T extends Object declared in class MyStack\

MyStack.java:11: warning: [unchecked] unchecked cast
            T[] b = (T[])new Object[size*2];
                         ^
  required: T[]
  found:    Object[]
  where T is a type-variable:
    T extends Object declared in class MyStack
2 warnings

So bottom line, the problem is due to the creation of the generic type array. To solve this read this link: https://stackoverflow.com/a/530289/588532

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=18906&siteId=1