java - Casting a list of concrete objects to abstract types -


this has been asked before here, solution showing warning saying "unchecked cast". there safer way this. code 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 ok, but... dog dog = dogvector.get(0); // runtime exception - there's animal, not dog in vector. 

there reason why compiler won't allow casting types different generic types. can bypass restriction, lead serious problems in runtime (*classcastexception*s).

edit:

the problem have return vector animals, create vector of dogs or cats depending on conditions. can 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; } 

Comments

Popular posts from this blog

ios - iPhone/iPad different view orientations in different views , and apple approval process -

java Extracting Zip file -

C# WinForm - loading screen -