user445338
user445338

Reputation:

Delete elements from Vector without using Iterator

Hi I'm trying to delete certain elements from a vector. I have a solution working, but to me it's not elegant or ideal. I'm in MIDP so I don't have access to Iterator class. Any ideas what's the best way to implement it?

Current code:

    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;
        }
    }

Upvotes: 0

Views: 252

Answers (2)

GreyGeek
GreyGeek

Reputation: 948

You can use the way they do it in c++ (std::remove_if).The basic idea is to push all the element you want to delete at the end of the vector , then resize the vector in one shot. It goes like this : (sorry if my java is a bit rusty)

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++;
}
}

All that all the element from [0-j[ are the good element , and the element from [j-size-1[, the bad one:

myVector.resize(j);

Upvotes: 1

Mikhail Vladimirov
Mikhail Vladimirov

Reputation: 13890

For me the best way would be:

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;

Or, if you only need to remove very few elements:

for (int i = myVector.size () - 1; i >= 0; i--)
{
    if (((MyObject)myVector.get (i)).shouldBeDeleted ())
        myVector.remove (i);
}

Upvotes: 0

Related Questions