Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing an integer from a list

Tags:

java

list

How can I propperly check to see if a List has a defined Integer?

private List<Integer> itemsToDrop = new ArrayList<Integer>();
private int lastRateAdded, lastDropAdded;


if(itemsToDrop.contains(lastDropAdded))
{
      itemsToDrop.remove(lastDropAdded);

}
itemsToDrop.add(DropConfig.itemDrops[npc][1]);
lastRateAdded = itemRate;
lastDropAdded = DropConfig.itemDrops[npc][1];

However, this is throwing the following error

java.lang.IndexOutOfBoundsException: Index: 526, Size: 1

SO, I need to figure out how to properly check to see if an Integer is stored in the List or not

like image 297
Christian Tucker Avatar asked Dec 26 '22 17:12

Christian Tucker


1 Answers

List<Integer> list = new ArrayList<Integer>(Arrays.asList(5, 10, 42));
if (list.contains(10)) {
    list.remove(10); // IOOBE
}

The problem with the above code is that you're actually not calling List#remove(Object) but List#remove(int), which removes the element at given index (and there's no element at index 10).

Use instead:

List<Integer> list = new ArrayList<Integer>(Arrays.asList(5, 10, 42));
if (list.contains(10)) {
    list.remove((Integer) 10);
}

That way, you force the compiler to use the List#remove(Object) method.

like image 145
sp00m Avatar answered Dec 28 '22 05:12

sp00m