How to Cast a Vector to Vector in Java?

前端 未结 2 1301
情歌与酒
情歌与酒 2021-01-23 09:28

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 e

相关标签:
2条回答
  • 2021-01-23 09:59

    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 讨论(0)
  • 2021-01-23 10:01

    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.

    0 讨论(0)
提交回复
热议问题