Java: security type - untested cast

Here is my code:

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

He gives this warning for LinkedList:

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

Why is he complaining about a linked list and not MyGenome?

+4
source share
2 answers

Because here:

 MyGenome genome = (MyGenome) data[0]; 

You do not use generics

And here

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

You use them.

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

But it would be better to have such an object:

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

And you need the methods to return the right things, before the correct conversion, so that you are done:

 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 these methods, you need to make the correct conversions.

+3
source

Java complains so much when you apply a non-parameterized type (object) to a parameterized type (LinkedList). This is to tell you that it can be anything. This really is no different from the first cast, except for the first one that throws a ClassCastException, if it's not that type, but the second won't.

It all comes down to erasing the type. LinkedList at runtime is just a LinkedList. You can put anything into it and it will not throw a ClassCastException, as in 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 that the content will have the class Something.

Another aspect of this is that arrays in Java are covariant , which means that they store information like runtime. For instance:

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

will throw an exception. But:

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

is completely legal.

+12
source

All Articles