0

嗨,我正在尝试从向量中删除某些元素。我有一个可行的解决方案,但对我来说它并不优雅或不理想。我在 MIDP 中,所以我无权访问 Iterator 类。任何想法什么是实现它的最佳方式?

当前代码:

    int size = myVector.size();
    Object[] copyofObjects = new Window[size];
    myVector.copyInto(copyofObjects);
    boolean didDelete = false;

    for(int i = 0; i < size; i++)
    {
        Object o = copyofObjects[i];
        if(o.shouldBeDeleted())
        {
            myVector.removeElementAt(myVector.indexOf(o));
            continue;
        }
    }
4

2 回答 2

1

您可以使用他们在 c++ 中执行此操作的方式(std::remove_if)。基本思想是将要删除的所有元素推到向量的末尾,然后一次性调整向量的大小。它是这样的:(对不起,如果我的 java 有点生锈了)

for (int i = 0 , j = 0; i < size ; i++){
     MyObject o = (MyObject)myVector.get (i);
    if (!o.shouldBeDeleted ()){
        //swap the element
        temp = myVector[i]
        myVector[i] = myVector[j]
        myVector[j] = temp;
        j++;
}
}

所有来自 [0-j[ 的元素都是好元素,来自 [j-size-1[ 的元素是坏元素:

myVector.resize(j);
于 2013-02-04T18:08:33.053 回答
0

对我来说最好的方法是:

Vector newVector = new Vector ();
for (int count = myVector.size (), i = 0; i < count; i++)
{
    MyObject o = (MyObject)myVector.get (i);
    if (!o.shouldBeDeleted ())
        newVector.add (o);
}
myVector = newVector;

或者,如果您只需要删除很少的元素:

for (int i = myVector.size () - 1; i >= 0; i--)
{
    if (((MyObject)myVector.get (i)).shouldBeDeleted ())
        myVector.remove (i);
}
于 2013-02-04T17:58:18.690 回答