zoukankan      html  css  js  c++  java
  • ArrayList 一个面试题

    我们现在有一个集合,集合里面有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;
        }
    

      

  • 相关阅读:
    Rundll32
    ASP.NET MVC3 中整合 NHibernate3.3、Spring.NET2.0 时 Session 关闭问题
    页面内容排序插件jSort的使用
    jQuery实现等比例缩放大图片
    CSS 样式使用
    AspNetPager 样式以及使用(漂亮)
    怎么提高Jquery性能
    java 常见下载合集
    ES6 rest参数和扩展运算符
    21.Decorator修饰器
  • 原文地址:https://www.cnblogs.com/jiangyaxiong1990/p/10414107.html
Copyright © 2011-2022 走看看