I have a problem when I'm adding Entity objects to my ArrayList (here called entities). Each Entity-object has a long ID, int x-position and y-position
First I check if the list is empty, with it should be at start. If I add a 2nd Entity-object I check if the id of the object exist and if so, the positions of the Entity-object is updated. If the object does not exist, it should be added.
My problem is that the size of the ArrayList gets enormous and I'm not sure to how to fix it.
All of the following code is located in an update() method that is continuously run.
/**
* Method that checks if the entity exist or not.
* @param ent - The Entity that should be updated or added.
*/
public void checkEntity(Entity ent){
if(entities.isEmpty()){
entities.add(ent);
}
else{
for(ListIterator<Entity> li = entities.listIterator(); li.hasNext();){
Entity next = li.next();
if(next.getID() == ent.getID()){
// System.out.println("id: " + next.getID() + " xPos: " + next.getXPos() + " yPos: " + next.getYPos() + " type: " + next.getType());
next.setXPos(xPos);
next.setYPos(yPos);
}
else{
li.add(ent);
}
System.out.println(entities.size());
}
}
The problem is that you're adding a new entry into the list every time you find an entry which doesn't have the same ID... your add
call is inside your loop, and it shouldn't be.
Basically, you should have something like:
public void checkEntity(Entity entity) {
for (Entity candidate : entities) {
if (candidate.getID() == entity.getID()) {
candidate.setXPos(entity.getXPos());
candidate.setYPos(entity.getYPos());
// Found a matching entity, so we're done now.
// This is important, so we don't add the entity again.
return;
}
}
// Haven't found it, so add it to the list
entities.add(entity);
}
Note that this is going to be very inefficient if you add a lot of entities. It would be a lot more efficient to have a map from entity ID to entity... then you don't need to check every entity every time.
See more on this question at Stackoverflow