lost in iterations

edited July 2015 in Questions about Code

Hello

is it me or is there a problem with this thing ?

ArrayList<String> items;

void setup() {
  items = new ArrayList<String>();
  items.add(new String("A")); 
  items.add(new String("B")); 
  items.add(new String("C")); 
  items.add(new String("D"));
  items.add(new String("E"));
  items.add(new String("F"));
  items.add(new String("G"));
  items.add(new String("H"));
  println(items);
}

void draw() {
  for (int i = 0; i < items.size (); i++) {
    println("i = " + i );
    items.remove(i);
  }
  if(items.size () != 0){
  println(items);
  } else{
    println(items);
    noLoop();
  }
}

I mean not to be too explicit, I'm kind of playful you know ;) if you run the code and you don't see anything wrong... then it's me :]

Answers

  • How can we know what's wrong if we don't know whats right :D

    Especially as I can't run your code on my tablet.

  • Answer ✓

    I can see one problem you must be careful about remove elements from a list while iterating over the list. In this situation it is not recommended to use list.remove (element) and the usual way is ti use an Iterator object to traverse the list and remove elements.

  • @GoToLoop has some example code of safely removing elements from a list without the need for an Iterator :)

  • edited July 2015 Answer ✓

    In short, don't use a regular for (;;) loop when remove() is present!
    Rather, do a "backwards" for (;;) loop: http://forum.Processing.org/two/discussions/tagged/backwards

    Also, new String("A") can be replaced w/ "A"!!!

  • :D

    thank you very much

    ArrayList<String> items;
    
    void setup() {
      items = new ArrayList<String>();
      items.add("A"); 
      items.add("B"); 
      items.add("C"); 
      items.add("D"); 
      items.add("E"); 
      items.add("F"); 
      items.add("G"); 
      items.add("H"); 
      println(items);
    }
    
    void draw() {
      for (int i = items.size()-1; i >= 0; i--) {
        println("i = " + i );
        items.remove(i);
      }
      if (items.size () != 0) {
        println(items);
      } else {
        println(items);
        noLoop();
      }
    }
    
Sign In or Register to comment.