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
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.
Supposing you have a list
private List<Integer> itemsToDrop = new ArrayList<Integer>();
To answer your questions:
A : To check if an integer belongs to a list of integers, you can use .contains()
itemsToDrop.contains(item)
, where item is an integer. This will return true
or false
.
B : To add
itemsToDrop.add(item)
C : To remove
itemsToDrop.remove(item)
Edit: Just to be clear, the initial post contained 3 questions which I answered
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.