开发者

How to Cast a Vector<ObjectA> to Vector<ObjectB> in Java?

开发者 https://www.devze.com 2023-02-16 16:38 出处:网络
I am using JComboBox with a custom class object, and the equals method is over-ridden, and integrated very deeply into the code.

I am using JComboBox with a custom class object, and the equals method is over-ridden, and integrated very deeply into the code.

The problem is that if two objects are equal in a JComboBox drop down, then if one is selected all are selected, and the get selected index returns -1.

Is there a ways to cast a Vector<ObjectA> to a Vector<ObjectB>? I tried

Vector<Clas_2> v_temp=(ca.courses.get(i).classes);

and

Vector<Clas_3> v_temp=(ca.courses.get(i).classes);

Where Clas_2 is a parent of Clas_1 and Clas_3 is a extends of Clas_1, but neither of them compile.

All i need is JComboBox not to use the over-ridden equals method.

*Note I know I can cast each individual elem开发者_高级运维ent into a new array, but would rather have a more memory efficient solution.


Changing the type you declare a variable as in code won't change what equals() method is called. It will always be the overriden one, irrespective of what you cast it to. This is how polymorphism works. You'll need to create a different class if you want a different implementation of equals.


No, not without being type-unsafe. But you can cast Vector<Clas_1> to Vector<? extends Clas_2> though which should solve your problem.

Since Clas_2 is a parent class of Clas_1, anything you get from a Vector<Clas_1> is an instance of Clas_2, but you cannot add any Clas_2 to a Vector<Clas_1> since not all instances of of Clas_2 are instances of Clas_1. The extends syntax makes that distinction.

0

精彩评论

暂无评论...
验证码 换一张
取 消