import java.util.ArrayList;
/**
*
* @author Matthew Casperson
*
* This class maintains a collection of objects where the collection is expected to be modified
* while iterating over it. By putting all new and removed objects in seperate lists and then
* syncing then with the main collection with the sync() function we can avoid the exceptions and
* logic errors that arise if you try to modify a collection while iterating over it.
*
*/
public class EngineManagerCollection<T>
{
// a collection of the BaseObjects
protected ArrayList<T> mainCollection = new ArrayList<T>();
// a collection where new BaseObjects are placed, to avoid adding items
// to baseObjects while in the baseObjects collection while it is in a loop
protected ArrayList<T> newCollection = new ArrayList<T>();
// a collection where removed BaseObjects are placed, to avoid removing items
// to baseObjects while in the baseObjects collection while it is in a loop
protected ArrayList<T> removedCollection = new ArrayList<T>();
public ArrayList<T> getMainCollection()
{
return mainCollection;
}
public ArrayList<T> getRemovedCollection()
{
return removedCollection;
}
public void addObject(T baseObject)
{
newCollection.add(baseObject);
}
public void removeObject(T baseObject)
{
removedCollection.add(baseObject);
}
public void sync()
{
insertNewBaseObjects();
removeDeletedBaseObjects();
}
protected void insertNewBaseObjects()
{
for (T baseObject : newCollection)
mainCollection.add(baseObject);
newCollection.clear();
}
protected void removeDeletedBaseObjects()
{
// insert the object according to it's z position
for (T removedObject : removedCollection)
mainCollection.remove(removedObject);
removedCollection.clear();
}
}
|