Search code examples
javatype-safety

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?


Solution

  • 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.