如何转换 Vector到 Vector在Java中?
我将 JComboBox 与自定义类对象一起使用,并且 equals 方法被重写,并非常深入地集成到代码中。
问题是,如果 JComboBox 下拉列表中的两个对象相等,那么如果选择了其中一个,则所有对象都会被选中,并且获取选定索引将返回 -1。
有没有办法将 Vector
转换为 Vector
? 我尝试
Vector<Clas_2> v_temp=(ca.courses.get(i).classes);
过,
Vector<Clas_3> v_temp=(ca.courses.get(i).classes);
其中 Clas_2
是 Clas_1
的父级,而 Clas_3
是 Clas_1
的扩展,但它们都不是编译。
我需要的是 JComboBox 不要使用重写的 equals 方法。
*注意我知道我可以将每个单独的元素转换为一个新数组,但宁愿有一个更有效的内存解决方案。
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 element into a new array, but would rather have a more memory efficient solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更改代码中声明变量的类型不会更改调用的
equals()
方法。无论您将其投射到什么位置,它都将始终是被覆盖的。这就是多态性的工作原理。如果您想要不同的 equals 实现,则需要创建一个不同的类。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.不,不是类型不安全的。但是您可以将
Vector
转换为Vector
虽然这应该可以解决你的问题。由于
Clas_2
是Clas_1
的父类,因此您从Vector
获取
的任何内容都是Clas_2
的实例,但您无法添加
任何Clas_2
到Vector
,因为并非Clas_2
的所有实例都是Clas_1
的实例。extends
语法做出了这种区分。No, not without being type-unsafe. But you can cast
Vector<Clas_1>
toVector<? extends Clas_2>
though which should solve your problem.Since
Clas_2
is a parent class ofClas_1
, anything youget
from aVector<Clas_1>
is an instance ofClas_2
, but you cannotadd
anyClas_2
to aVector<Clas_1>
since not all instances of ofClas_2
are instances ofClas_1
. Theextends
syntax makes that distinction.