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.

0

3 Answers 3

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
        {}
}
}
Sign up to request clarification or add additional context in comments.

1 Comment

It could also help avoiding NPE's to invoke equals() on the literal String "FREE" instead.
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?

1 Comment

I think you have a mistake in your for loop. Shouldn't it.hasNext() be the condition, not the update?
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.