views:

897

answers:

2

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?

+3  A: 

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.

cletus
A: 

Because here:

MyGenome genome = (MyGenome) data[0];

You are not using generics

And here

LinkedList<Species> breeds = (LinkedList<Species>) data[1];

You are using them.

That's just a warning, you are mixing types in the data array. If you know what are you doing ( I mean, if the second element do contains a LinkedList ) you can ignore the warning.

But better would be to have an object like this:

class Anything {
    private Object [] data;
    public Anything( Object [] data ) {
         this.data = data;
    }
    public Gnome getGnome() {
    .....
    }
    public List<Species> getBreeds() {
    ......
    }
 }

And have to methods returning proper things, prior to a correct conversion so you end up with:

Anything anything = new Anything( GeneComparison.readData(files) );
MyGenome genome             = anything.getGnome(); // similar to data[0]
LinkedList<Species> breeds = anything.getBreeds(); // similar to data[1];

Inside those methods you have to do proper transformations.

OscarRyz