0

I have two vectors like this :

Vector<Animal> vAM = new Vector<Animal>();
Vector<Cat> vCat = new Vector<Cat>();

Is it possible to cast the vAM vector into the vCat vector ? If not, then how should it be done ?

Update : The reason I mentioned this is I have a certain conversion here in my code which does not throw compile time exception , but it throws a run time exception . Hence I wanted to know whether there is any other way of doing this .

The Dark Knight
  • 5,455
  • 11
  • 54
  • 95
  • Related: http://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-arent-javas-generics-implicitly-p – Marco13 Feb 03 '15 at 10:56

2 Answers2

2

The cast you have in mind is just a compile-time artifact: you want the compiler to re-interpret an expression of the static type Vector<Animal> as an expression of type Vector<Cat>. That kind of re-interpretation violates static type safety, which is why it causes a compiler error.

If you really have the need for this, for example due to some mismatches in a 3rd-party API you are using, there is a way around the compiler check, but you'll still need to @SuppressWarnings:

vCat = (Vector<Cat>)(Vector)vAM;

Note that by doing this you lose the compiler's guarantee that vAM actually only contains cats.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
1

Yes, you can use a direct cast. But i would not recommend to do so, as not every animal can be a cat. This would lead to ClassCastExcpetions.

I don't understand the need to do this cast, so I think its better to rethink the design of your program.

Steffen
  • 341
  • 1
  • 12