如何将列表中的对象添加到向量中?

huangapple go评论54阅读模式
英文:

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 = &lt;Objects returned from SQL SELECT results&gt;

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 &lt; 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&lt;&gt;(list1);

例如 -

List&lt;String&gt; strings = Arrays.asList(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;);
List vecor1 = new Vector(strings);
System.out.println(vecor1);
英文:

Vector also implements List Interface, so you can try something like -

List vector1 = new Vector&lt;&gt;(list1);

For example -

List&lt;String&gt; strings = Arrays.asList(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;);
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);

huangapple
  • 本文由 发表于 2020年10月16日 17:28:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/64386496.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定