Java Convert Object[] Array to Vector

不羁岁月 提交于 2019-11-29 03:56:38
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.

In J2ME, you're stuck iterating over the array and add the elements one by one.

Vector v = new Vector();
for (int i = 0; i < this.elements.length; i++) {
    v.add(this.elements[i]);
}

A simplified comparator which does basically the same thing.

final static class ContactsListComparatorByFirstName implements Comparator {
    public int compare(Object o1, Object o2) {
            // Sticky Entries Implementation
        ContactsListObject clo2 = (ContactsListObject) o2;
        ContactsListObject clo1 = (ContactsListObject) o1;
        if (clo2.getSticky()) return 1;
        if (clo1.getSticky()) return -1;
        return clo1.get_contactFirstName().compareTo(clo2.get_contactFirstName());
    }
}    

Using generics and ?: it would be just

static final class ContactsListComparatorByFirstName implements Comparator<ContactsListObject> {
    public int compare(ContactsListObject clo1, ContactsListObject clo2) {
        return clo2.getSticky() ? 1 : // Sticky Entries Implementation
            clo1.getSticky() ? -1 :
            clo1.get_contactFirstName().compareTo(clo2.get_contactFirstName());
    }
}

But to answer your question... (oh I see Tom has what I would put already)

imho your only viable option is:

public Vector getListElements()
    Vector vector = new Vector(this.elements.length);

    for (int i = 0; i < this.elements.length; i++) {
        vector.add(this.elements[i]);
    } 

    return vector;
}
camickr
  1. Copy the array elements to the Vector, or

  2. Use Arrays.asList(...) to return a List, which isn't exactly a Vector, but you should be coding the List interface anyway.

A reasonably concise way to do it is something like:

Object[] xx = { 1, "cat", new Point(100,200) };
Vector vv = new Vector(Arrays.asList(xx));
System.out.println("vv=="+vv.toString());

But y'all knew that already, I guess.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!