do{
System.out.println("inside do");
for (int i = 0; i < i2; i++) {
String s2 = m_area.m_items.get(i).returnName();
if (s2.contains(s)) {
itemexist_check = true;
player.addItem(m_area.m_items.get(i));
m_area.m_items.remove(i);
} else {
//do nothing
}
}
itemexist_check = true;
}while(itemexist_check == false);
When this do statement is run, it will happily perform the “player.addItem(m_area.m_items.get(i))”, but when it gets to “m_area.m_items.remove(i)” (m_items is a LinkedList) , it throws an “OutOfBoundsException: Index 1, Size 1”. Via printing the size of the LinkedList, as well as printing the value of “i”, I have determined that prior to the “m_area.m_items.remove(i)”, the size of the LinkedList is 2, and the value of “i” is 0. I understood why it threw the exception. There is obviously no Element 0 in the LinkedList. What I don’t know is, why didn’t it throw the exception on the “player.addItem(m_area.m_items.get(i))”? Something isn’t right here, please help.
Thank you
The savest way to deal with list traversal + removal is to separate the two. Hence, iterate through your list using a standard forearch loop (also much easier and faster than
getcalls). Instead of removing the item, add it to a separate list and after your loop usem_area.m_items.removeAll(removedElementsList).