ArrayList 一個面試題

咱們如今有一個集合,集合裏面有100個隨機數,獲取其中的基數;java

//假設咱們獲得了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一個新特性:dom

ArrayList在remove的過程當中,會刪除列表中指定位置的元素。將任何後續元素向左移動(從它們的索引中減去一個)this

/**
     * 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;
    }
相關文章
相關標籤/搜索