Iterating through a list and allowing it to have an item removed at the same time (NOT ITERATOR)

ATTENTION: I CANNOT know if doSomething will remove the element or not. This is an exceptional case that my data structure needs to handle.

My problem is simples:

int size = list.size();
for(int i = 0; i < size; i++) {
   MyObj mo = list.get(i);
   mo.doSomething();
}

Now if doSomething() remove mo from the list, I eventually get an ArrayIndexOutOfBounds because the list has now shrunk.

What data structure should I use to allow iteration with the possibility of removing? I can NOT use an iterator here, in other words, I can NOT make doSomething return a boolean and call iterator.remove(). The data structure has to somehow handle the situation and continue to iterator through the rest of the elements still there.

EDIT: I CANNOT know if doSomething will remove the element or not. This is an exceptional case that my data structure needs to handle.

Part II => Making a smart listeners notifier to avoid code duplication everywhere

Answers


You can use an ArrayList, for example, as long as you update the index and size when something is removed.

List<MyObj> list = new ArrayList<MyObj>();
int size = list.size();
for(int i = 0; i < size; i++) {
    MyObj mo = list.get(i);
    mo.doSomething();
    if (size > list.size()) {
        size = list.size();
        i--;
    }
}

This only works if the item removed is the last one examined. For other changes to the list you will have to have more complicated logic.


Need Your Help

How do I style the scrollbars of a GWT DataGrid

java gwt

What is the proper way to override the style of the GWT DataGrid scrollbars? To be more specific, I want to have a constant opacity of 1.0 instead of the default transition effect.

Is there a pattern for propagating configuration state down an object graph?

dependency-injection circular-dependency god-object

I'm trying to avoid creating a monster class, and I noticed a not-so-good pattern and was curious if anyone had any insight into this problem.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.