从通用列表Java中删除项目?

从通用列表Java中删除项目?

问题描述:

我需要从Java的通用列表中删除一个项目,但是我不知道该怎么做.如果它是一个int列表,则将其设置为零,如果它是字符串,则将其设置为null.我该如何使用通用列表做到这一点,而不能使用Arraylist或类似方法,我必须自己编写该方法.

I need to remove an item from a generic list in java, but I don't know how to do this. If it was a list of int, I would just set it to zero, if it was strings I would set it to null. How can I do this with a generic list, and I can't use an methods of Arraylist or anything like that, I have to write the method myself.

您可以使用 List.remove(int) .您还可以调用 Iterator.remove() 在迭代List时.因此,例如,要删除List中的所有项目,您可以

You can remove an individual object instance with List.remove(Object) or you can remove a specific instance from a specific index with List.remove(int). You can also call Iterator.remove() while you iterate the List. So, for example, to remove every item from a List you could do

Iterator<?> iter = list.iterator();
while (iter.hasNext()) {
  iter.remove();
}