javac complaining about unchecked cast

63 views Asked by At

I'm a JavaScript developer doing a Java exercise and I could use help.

When I try to compile with javac, I get: "uses unchecked or unsafe operations."

Do I need to worry about that?

Am I doing this right?

MacBook-Pro-3:Documents garrettsmith$ javac codepoop/*.java -Xlint:unchecked
codepoop/GArrayList.java:30: warning: [unchecked] unchecked cast
    return (T) elements[i];
                       ^
  required: T
  found:    Object
  where T is a type-variable:
    T extends Object declared in class GArrayList
1 warning

GArrayList:

import java.util.Arrays;

public class GArrayList<T> {

  private Object elements[];
  private int size = 0;

  public GArrayList() {
    elements = new Object[1];
  }

  public T get(int i) {
    return (T) elements[0]; // javac complains about this line.
  }
}
1

There are 1 answers

2
drkblog On

You declared a generic class but you are not using the generic type T to store data. Because you are using an array you actually can't. In this case you can just suppress the warning provided that you class ensures only objects of type T are going to be added.

public class GArrayList<T> {

  private Object elements[];
  private int size = 0;

  public GArrayList() {
    elements = new Object[1];
  }

  @SuppressWarnings("unchecked")
  public T get(int i) {
    return (T) elements[0]; // javac complains about this line.
  }

  public void add(T element) {
    elements[index++] = element;
  }
}

Note the add() method receives only T and the array is private so it can't be accessed from outside the class. But, yeah, the add() method won't work. It's just for showing how you can ensure the type safety by yourself.