在尝试ArrayList的removeRange方法时,发现该方法不可用?如下
调用:arrayList.removeRange(2,3);
报错:The method removeRange(int, int) from the type ArrayList<Object> is not visible
原因: removeRange(int fromIndex, int toIndex) method is protected method in ArrayList. A protected method is accessed in class, subclasses and in a package, but not public. Therefore we extend the class to arraylist.
忽略了该方法的权限,protected 只能在当前类、同一包、子孙类中可用,所以直接调用会报错。
那要怎么调用呢?让一个类继承它就好了,然后该类就可以调用该方法了。
例如:
public class SubArrayList extends ArrayList {
public static void main(String[] args) {
SubArrayList arrayList = new SubArrayList();
Integer integer = 0;
Integer integer1 = 1;
Integer integer2 = 2;
Integer integer3 = 3;
Object object = null;
arrayList.add(integer);
arrayList.add(integer1);
arrayList.add(integer2);
arrayList.add(integer3);
arrayList.add(object);
// 移除下标为1,2的元素
arrayList.removeRange(1, 3);
// 常规for循环遍历
System.out.println("常规for循环遍历:");
for (int i = 0; i < arrayList.size(); i++) {
System.out.println("object:" + arrayList.get(i));
}
}
}
输出为:
常规for循环遍历:
object:0
object:3
object:null
注:这种类似数组下标区间一般都是取下不取上,即[min, max) ,包含min而不包含max。