0

I have class with ArrayList of teams and i want remove team which name is "FREE";

so i tried:

 public void removeFree()
{

    for (int i = 0 ; i < numberOfTeams ; i++ )
    {
        if (this.getListOfTeams().get(i).getName() == "FREE")
        {
            this.getListOfTeams().remove(i);
        }
        else
        {}
    }
}

That makes my app crash.

n0hepe
  • 188
  • 1
  • 2
  • 11

3 Answers3

3

Use, equals() method to check if two strings are meaningfully equal. == operator just checks if two reference variables refer to the same object.

    if (this.getListOfTeams().get(i).getName() == "FREE")

should be

    if (this.getListOfTeams().get(i).getName().equals("FREE"))

Also to add more, even if you use equals() you'd get ConcurrentModificationException as you are removing the elements from the arrayList while iterating over it. you have to use an iterator and remove elements from it rather.

Iterator<Team> itr = getListOfTeams.iterator();
while(itr.hasNext()){
  if (itr.next().getName().equals("FREE"))
        {
            itr.remove();
        }
        else
        {}
}
}
PermGenError
  • 45,977
  • 8
  • 87
  • 106
2

To remove an element from a List while iterating it, it's safer to use an Iterator along with the remove method:

for (Iterator it = getListOfTeams().iterator;it.hasNext();) {
    String name = it.next();
    if ("FREE".equals(name) {
        it.remove();
    }
    else{}
}

Please note how String value comparison in Java should usually be done by means of the String.equals() method. == is the reference equality operator. See How do I compare strings in Java?

Community
  • 1
  • 1
Xavi López
  • 27,550
  • 11
  • 97
  • 161
  • I think you have a mistake in your `for` loop. Shouldn't `it.hasNext()` be the condition, not the update? – jlordo Feb 11 '13 at 11:02
0

You are trying to remove an item while you are looping the same ArrayList. You need to clone first, iterate the cloned list and then delete the items of the first pointer.

so consider this:

List<Object> arrayToIterate = getListOfTeams().clone();
for (int i = 0 ; i < numberOfTeams ; i++ )
{
    if (tarrayToIterate.get(i).getName().equals("FREE"))
    {
        this.getListOfTeams().remove(i);
    }
    else
    {}
}

Also you are comparing an string with == instead of equals.

PaNaVTEC
  • 2,505
  • 1
  • 23
  • 36