Java Convert Object[] Array to Vector

后端 未结 6 2033
灰色年华
灰色年华 2020-12-16 19:21

What\'s the best way to convert an Object array to a Vector?

JDE < 1.5

public Vector getListElements()
{
  Vector myVector = this.elements;
  retu         


        
6条回答
  •  感动是毒
    2020-12-16 19:53

    return new Vector(Arrays.asList(elements));
    

    Now, it may look as if you are copying the data twice, but you aren't. You do get one small temporary object (a List from asList), but this provides a view of the array. Instead of copying it, read and write operations go through to the original array.

    It is possible to extends Vector and poke its protected fields. This would give a relatively simple way of having the Vector become a view of the array, as Arrays.asList does. Alternatively, just copying data into the fields. For Java ME, this is about as good as it gets without writing the obvious loop. Untested code:

    return new Vector(0) {{
        this.elementData = (Object[])elements.clone();
        this.elementCount = this.elementData.length;
    }};
    

    Of course, you are probably better off with a List than a Vector. 1.4 has completed its End of Service Life period. Even 1.5 has completed most of its EOSL period.

提交回复
热议问题