简体   繁体   中英

Casting a list of concrete objects to abstract types

This has been asked before here , but the solution is showing a warning saying "Unchecked cast". Is there a safer way to do this. Code is given below.

public abstract class Animal {
.
..
public class Dog extends Animal{

..
    public Vector<Animal> myFunc(String[] args) {
        // TODO Auto-generated method stub

        Vector<Dog> arVector = new Vector<Dog>();
        return  (Vector<Animal>)(List<?>) arVector; 

    }

It's not safe because:

Vector<Dog> dogVector = new Vector<Dog>();
Vector<Animal> animalVector = (Vector<Animal>)(List<?>) dogVector;
animalVector.add(new Animal()); // seems to be ok, but...
Dog dog = dogVector.get(0); // Runtime exception - there's Animal, not Dog in your Vector.

There is a reason why compiler won't allow you casting types with different generic types. You can bypass this restriction, but this will probably lead to serious problems in the runtime (*ClassCastException*s).

EDIT:

The problem is that you have to return a Vector with Animals, but you create Vector of Dogs or Cats depending on some conditions. What you can do is:

public Vector<? extends Animal> myFunc(String[] args) {
   Vector<Dog> vector = new Vector<Dog>();
   // ...
   return vector;
}

or:

public Vector<Animal> myFunc(String[] args) {
   Vector<Animal> vector = new Vector<Animal>();
   vector.add(new Dog());
   return vector;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM