简体   繁体   English

从列表中删除整数

[英]Removing an integer from a 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 java.lang.IndexOutOfBoundsException:索引:526,大小: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). 上面代码的问题是你实际上没有调用List#remove(Object)而是List#remove(int) ,它删除了给定索引处的元素(并且索引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. 这样,您强制编译器使用List#remove(Object)方法。

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() :要检查整数是否属于整数列表,可以使用.contains()

itemsToDrop.contains(item)

, where item is an integer. ,其中item是一个整数。 This will return true or false . 这将返回truefalse

B : To add B :添加

itemsToDrop.add(item)

C : To remove C :要删除

itemsToDrop.remove(item)

Edit: Just to be clear, the initial post contained 3 questions which I answered 编辑:为了清楚起见,最初的帖子包含3个我回答的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM