如何转换 Vector到 Vector在Java中?

发布于 2024-10-21 20:04:56 字数 628 浏览 7 评论 0原文

我将 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_2Clas_1 的父级,而 Clas_3Clas_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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

纸伞微斜 2024-10-28 20:04:56

更改代码中声明变量的类型不会更改调用的 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.

第几種人 2024-10-28 20:04:56

不,不是类型不安全的。但是您可以将 Vector 转换为 Vector 虽然这应该可以解决你的问题。

由于 Clas_2Clas_1 的父类,因此您从 Vector 获取的任何内容都是 Clas_2 的实例,但您无法添加任何Clas_2Vector,因为并非 Clas_2 的所有实例都是 Clas_1 的实例。 extends 语法做出了这种区分。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文