removeRange()坑

1、关于removeRange() 的用法,最近遇到下面的一道面试题,试问运行结果:

public class MyUtil extends ArrayList {
  public static void main(String [] args){
    MyUtil m = new MyUtil();
    m.add("w");
    m.add("x");
    m.add("y");
    m.add("z");
    m.removeRange(1,3);
    System.out.println(m.size() + "");
    MyUtil m2 = new MyUtil2().go();
   }
}
class  MyUtil2{
  MyUtil go(){
    MyUtil m2 = new MyUtil();
    m2.add("1");
    m2.add("2");
    m2.add("3");
    m2.removeRange(1,2);
    return m2;
  }
}

显然m2.removeRange(1,2);这一行报错,
提示说明 “‘removeRange(int, int)’ has protected access in ‘java.util.ArrayList’”
那么问题来了 removeRange为什么要标记成protected?
贴出源码如下,自己去追踪源码分析 ~~

protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,numMoved);

        // clear to let GC do its work
        int newSize = size - (toIndex-fromIndex);
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        size = newSize;
    }

提供参考
https://www.cnblogs.com/hzmark/archive/2012/12/19/ArrayList_removeRange.html

你可能感兴趣的:(removeRange()坑)