1

I have an ArrayList of EnemyVehicle objects. Its name is enemies. When I try to delete an object of EnemyVehicle class, just like in this question, I get unexpected type error:

required: valuable
found: value

That's my code:

private void enemiesTurn()
{
    for(int i = 0; i<enemies.size(); i++)
    {
        if(enemies.get(i).isDestroyed())
        {
            enemies.add(getNewRandomVehicle(difficulty));
            p1.setScore(p1.getScore() + 20);
            enemies.get(i) = null;
        }
    }    
}

What can i do?

Community
  • 1
  • 1
Emre
  • 933
  • 15
  • 27
  • wouldn't you prefer to remove the object from the ArrayList? if that is the case you should consider the order of your iteration, as described [here](http://stackoverflow.com/questions/10714233/remove-item-from-arraylist) – Carlos Monroy Nieblas Nov 02 '16 at 20:26

2 Answers2

1

instead of enemies.get(i) = null; do enemies.remove(enemies.get(i));

EDIT: This is because enemies.get(i) is a value, not a variable and you cannot use it on the lefthand side of operations. The lefthand side of operations must include variable in some manner.

theKunz
  • 444
  • 4
  • 12
  • But i am trying to delete the object from memory, not from the arraylist – Emre Nov 02 '16 at 20:26
  • @EmreSülün You don't delete objects from memory. That's the garbage collector's job. – Kayaman Nov 02 '16 at 20:27
  • Although removing an element of `enemies` while iterating over it will result in a `ConcurrentModificationException`. – Kayaman Nov 02 '16 at 20:28
  • @EmreSülün Kayaman is correct. Unless you have a reference to the the object elsewhere, once you remove it from the arraylist the garbage collector will remove it from memory for you. – theKunz Nov 02 '16 at 20:29
  • I have one more question. What is the reason of this error? – Emre Nov 02 '16 at 20:30
0

When you're deleting stuff from an ArrayList or any List types. You should use an Iterator.

for (Iterator<ClassName> it = enemies.iterator(); it.hasNext();) {
     ClassName objectName = it.next();
     if(objectName.isDestroyed()) {
            enemies.add(getNewRandomVehicle(difficulty));
            p1.setScore(p1.getScore() + 20);
            it.remove();
     }
}
Christian Moen
  • 1,253
  • 2
  • 17
  • 31