问题
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.
回答1:
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();
}
回答2:
I would think that if you are implementing a list yourself you should move all elements after the element you are deleting down one position, set the last one to null, and if you are keeping track of the size of your list, reduce this by one. Something like this
public Object remove(int remove_index){
Object temp = list[remove_index];
for(int i=remove_index;i<size-1;i++){
list[i] = list[i+1];
}
list[--size] = null;
return temp;
}
回答3:
static <T> List<T> remove(List<? extends T> inputList, int removeIndex)
{
List<T> result = new ArrayList<T>( inputList.size() - 1 );
for (int i = 0 ; i < inputList.size() ; i++)
{
if ( i != removeIndex )
{
result.add( inputList.get(i) );
}
}
return result;
}
来源:https://stackoverflow.com/questions/26567815/removing-item-from-generic-list-java