Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Type safety - unchecked cast

Here is my code:

Object[] data = GeneComparison.readData(files);
MyGenome genome = (MyGenome) data[0];
LinkedList<Species> breeds = (LinkedList<Species>) data[1];

It gives this warning for the LinkedList:

Type safety: Unchecked cast from Object to LinkedList<Species>

Why does it complain about the linked list and not MyGenome?

like image 687
Nick Heiner Avatar asked Sep 29 '09 01:09

Nick Heiner


1 Answers

Java complains like that when you cast a non-parameterized type (Object) to a parameterized type (LinkedList). It's to tell you that it could be anything. It's really no different to the first cast except the first will generate a ClassCastException if it is not that type but the second won't.

It all comes down to type erasure. A LinkedList at runtime is really just a LinkedList. You can put anything in it and it won't generate a ClassCastException like the first example.

Often to get rid of this warning you have to do something like:

@SuppressWarning("unchecked")
public List<Something> getAll() {
  return getSqlMapClient.queryForList("queryname");
}

where queryForList() returns a List (non-parameterized) where you know the contents will be of class Something.

The other aspect to this is that arrays in Java are covariant, meaning they retain runtime type information. For example:

Integer ints[] = new Integer[10];
Object objs[] = ints;
objs[3] = "hello";

will throw a exception. But:

List<Integer> ints = new ArrayList<Integer>(10);
List<Object> objs = (List<Object>)ints;
objs.add("hello");

is perfectly legal.

like image 62
cletus Avatar answered Oct 03 '22 11:10

cletus