0

I'm trying to loop through an ArrayList, Here my old code which gives error when trying to add new NPC

if (npcs != null && npcs.size() > 1) {
        for (NPC npc: npcs) {
            if (npc != null)
                if(npc.getShow())
                    npc.render(g);
        }
    }

So I tried turning that into a ListIterator to fix the issue,

private void render(Graphics g) {
listIter = npcs.listIterator();
        int index = 0;
            while(listIter.hasNext())
            {
                if(shouldAdd(index+1)) {
                    index++;
                    listIter.add(npcs.get(index));

                }

                NPC current = (NPC) listIter.next();
                if (current != null) {
                    if (current.getShow()) {
                        current.render(g);
                    }
                }
            }

}
    private boolean shouldAdd(int index) {
            if (npcs.size() > index) {
                return true;
            }
            return false;
        }

Could someone please help me out and show me what I'm doing wrong?

  • Which error? Please show the stack trace. – Patrick Oct 10 '17 at 13:48
  • 2
    I don't see how those 2 pieces of code are supposed to produce the same outcome. In the first you don't add anything at all and only iterate it and call the render method if certain criteria are fullfilled. – OH GOD SPIDERS Oct 10 '17 at 13:52
  • 1
    Possible duplicate of [Java: adding elements to a collection during iteration](https://stackoverflow.com/questions/993025/java-adding-elements-to-a-collection-during-iteration) – Oneiros Oct 10 '17 at 13:55
  • Possible duplicate of [How To Use ListIterator?](https://stackoverflow.com/questions/43437541/how-to-use-listiterator) – Tiago_nes Dec 12 '17 at 12:05

0 Answers0