Logically,static double sumOfList(List<? extends Double> list)
will make the function become read-only mode ,then why list.remove()
can be compiled successfully
public class Extend_char {
public static void main(String[] args) {
{
List<Double> list = new ArrayList<>();
list.add(1.2);
list.add(2.2);
list.add(3.2);
System.out.println(sumOfList(list));
System.out.println(list);
}
static double sumOfList(List<? extends Double> list) {
double sum = 0;
for (int i=0; i<list.size(); i ) {
double n = list.get(i);
sum = sum n;
}
//list.add(new Double(5.5)); Cannot compile and call normally
list.remove(2.2); //Can compile and call normally
return sum;
}
}
CodePudding user response:
Logically,static double sumOfList(List<? extends Double> list) will make the function become read-only mode
See, that's the problem with programming. It's too complicated - so we provide oversimplified explanations.
You've been the victim of this. List<? extends Double>
is not a 'read only list'.
But I can see how someone who was trying to be helpful told you that it was.
See, the point of List<? extends Something>
is that it lets you provide a List<Something>
, or a List<SomeChildOfSomething>
. IF it is then possible to invoke .add(instanceOfSomething)
on such a thing, that's problem.
Imagine this method:
void foo(List<? extends Number> list) {
list.add(5); // an integer
}
List<Double> listOfDoubles = new ArrayList<Double>();
foo(listOfDoubles);
listOfDoubles.get(0); // oh dear. Now what?
See the problem? A solution is to ensure that all methods that would fail unless they know the precise type are disallowed. add
is such a method. So is addAll
and set
for obvious reasons. You can't invoke those unless you know the list is either of the exact type of the expression you're passing to those methods, or a supertype of it (which is why you can invoke .add
on a List<? super Double>
just fine).
But the methods that modify the list which do not cause such issues - basically everything that doesn't take a (collection of) elements of type T, such as .clear()
, .remove()
, removeIf
, etc?
Those are just fine.
TL;DR: List<? extends AThingie>
is not 'a read only list'. That's completely wrong. It is an understandable but oversimplified explanation though. Don't be too harsh on who told you this.