The short answer is: Use
al.subList(1, 3).clear();
The removeRange(int, int)
method is protected
. You can only invoke it from a subclass of ArrayList
or from a class within the same package as ArrayList
. See Controlling Access to Members of a Class.
The only way to access the removeRange
method is to subclass ArrayList
and make the method public. E.g.
public class RangeRemoveSupport<E> extends ArrayList<E> {
public void removeRange(int fromIndex, int toIndex) {
super.removeRange(fromIndex, toIndex);
}
}
But then your code must use the subclass. Thus your code depends on this subclass and not just depends on List
or ArrayList
.
A utility class within the same package to access it is not possible. E.g.
package java.util; // <- SecurityException
public class RemoveRangeSupport {
public static void removeRange(ArrayList<?> list, int from, int to){
list.removeRange(from, to);
}
}
This will cause a SecurityException
java.lang.SecurityException: Prohibited package name: java.util
.
because you are not allowed to define classes in java.util
for security reasons.
Nevertheless for other packages it might be a way.
I often use this strategy for tests. Then I put such a utility class in the same package as the production code to access some internals from tests that should normally not be accessible. This is an easy way without using a framework.
EDIT
Is there perhaps a function to replace items from range X..Y, to new items of a possible different size?
for example: this list "0,1,2,3,4", I replace from 1..3 with "a,b,c,d,e", will result with : "0,a,b,c,d,e,4".
List<String> list = new ArrayList<>(Arrays.asList("0", "1", "2", "3", "4"));
List<String> subList = list.subList(1, 4);
subList.clear();
subList.addAll(Arrays.asList("a", "b", "c", "d", "e"));
System.out.println(list);
will output
[0, a, b, c, d, e, 4]