Here is my code to take in a list of numbers and return the total sum of that list using a recursive method.
`public static int sum(ArrayList<Integer> list){
if (list.isEmpty()){
return 0;
}
int first = list.get(0);
ArrayList<Integer> rest = list.subList(1, list.size());
return first + sumList(rest);
}`
The error "cannot convert List to ArrayList" keeps popping up. Another error "sumList(ArrayList) is undefined for the type Main" also keeps popping up. Please help, what is the problem.
You can assign a
SubListto the interfaceList. I would encourage you to dig into the source code ofjava.util.Listandjava.util.ArrayListto see how the latter implements the sublist. Hint: it doesn't create anArrayList.Also, you should take this as a lesson to code to the interface, not to an implementation.
List.subList()returns aListso that implementations are free to return anything which implements theListinterface.One more note: use your IDE to help you do this. Write the right-hand side of the expression:
and with the cursor to the right of the semi-colon, hit the key-combo which brings up the quick assist context menu, and choose the "assign to local variable" (different text in each IDE) and the IDE will correctly ascertain what type to make the variable.