我们现在有一个集合,集合里面有100个随机数,获取其中的基数;
//假设我们得到了100个随机数 List<Integer> lists = new RandomArrayList<Integer>(100);
//方法一: for (int j =0; j< lists.size(); j++){ if(lists.get(j) % 2 == 0){ lists.remove(j--); } }
//方法二: for(int j = lists.size()-1; j > 0; j--){ if(lists.get(j) % 2 == 0){ lists.remove(j); } }
//方法三: for (int j =0; j< lists.size(); j++){ lists = lists.stream().filter(list -> list % 2 !=0).collect(Collectors.toList()); }
这倒题目主要考察了对ArrayList中remove方法的理解,以及java8一个新特性:
ArrayList在remove的过程中,会删除列表中指定位置的元素。将任何后续元素向左移动(从它们的索引中减去一个)
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*
* @param index the index of the element to be removed
* @return the element that was removed from the list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
浙公网安备 33010602011771号