英文:
How to add objects in a List to a Vector?
问题
我正在处理遗留代码。由于无法粘贴代码,我将提供一个示例。
List list1 = <从 SQL SELECT 结果返回的对象>;
基本上,list1 包含许多对象。我已经测试过确实存在这些对象,因为我在使用 getter 方法来确认列表中是否有对象。假设总共有 3 个对象。
我目前正在进行以下操作:
Vector vector1;
for (int i = 0; i < list1.size(); i++) {
vector1.add(list1.get(i));
}
但它不起作用。如何将对象从 List 转移到 Vector?
请注意,我不能更改数据类型,它必须保持为 List 和 Vector。我也尝试过将单个对象强制转换,还尝试过使用 `vector1.addElement()`,但都不起作用。
附注:我在 Eclipse v4.6 中作为 Java EE IDE Web Developer 进行开发。我的控制台没有显示任何内容,前端只是弹出一个错误,这就是我感到困惑的原因。如果我提供的信息不足,请原谅,我只是想确保我从 List 转移到 Vector 的方法是否正确。
英文:
I'm dealing with legacy code right here. I can't paste the code so I will give an example.
List list1 = <Objects returned from SQL SELECT results>
So basically list1 contains a number of objects. I've tested it was indeed there as I was using getters to confirm that there are objects in the list. Let's say there are a total of 3 objects.
I'm currently doing:
Vector vector1;
for (int i = 0; i < list1.size(); i++) {
vector1.add(list1.get(i));
}
But it does not work. How do I transfer objects from List to Vector?
Note that I cannot change the data type and it has to be List and Vector, I've tried adding casting to individual objects as well, and I have tested using vector1.addElement()
as well, but neither works.
P:S: Java EE IDE Web Developer in Eclipse v4.6. My console doesn't write anything, and my front end just "pops" an error, that is why I'm confused as well. Apologies if I do not have enough information, just wanted to make sure that my method to transfer objects from List to Vector is correct.
答案1
得分: 1
Vector还实现了List
接口,因此您可以尝试类似以下的操作 -
List vector1 = new Vector<>(list1);
例如 -
List<String> strings = Arrays.asList("A", "B", "C");
List vecor1 = new Vector(strings);
System.out.println(vecor1);
英文:
Vector also implements List
Interface, so you can try something like -
List vector1 = new Vector<>(list1);
For example -
List<String> strings = Arrays.asList("A", "B", "C");
List vecor1 = new Vector(strings);
System.out.println(vecor1);
答案2
得分: 1
你必须初始化vector1。
Vector vector1 = new Vector();
英文:
You have to initialize vector1.
Vector vector1 = new Vector();
答案3
得分: 0
因为Vector是一个列表,你可以使用Collections#copy函数。
Collections.copy(vector1, list1);
英文:
As Vector is a list, you can use Collections#copy
Collections.copy(vector1, list1);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论