Why does my subList not work for my Arraylist?

260 Views Asked by At

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.

3

There are 3 best solutions below

0
pfurbacher On

You can assign a SubList to the interface List. I would encourage you to dig into the source code of java.util.List and java.util.ArrayList to see how the latter implements the sublist. Hint: it doesn't create an ArrayList.

Also, you should take this as a lesson to code to the interface, not to an implementation. List.subList() returns a List so that implementations are free to return anything which implements the List interface.

One more note: use your IDE to help you do this. Write the right-hand side of the expression:

list.subList(1, list.size());

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.

0
Hemanth Baladari On

The return type of subList is List. That is the reason you are getting the message "The error "cannot convert List to ArrayList" keeps popping up."

To resolve this issue you need to type cast or change the variable reference to list.

Example:

  • ArrayList rest = (ArrayList) list.subList(1, list.size());

OR

  • List rest = list.subList(1, list.size());

for your another issue create a method name with sumList.

private static int sumList(List<Integer> rest) {
    // TODO Auto-generated method stub
    return 0;
}
0
strugglering On

use this ( the error reason you can refer above ):

public static int sum(List<Integer> list){
        if (list.isEmpty()){
            return 0;
        }
        int first = list.get(0);
        List<Integer> rest = list.subList(1, list.size());
        return first + sum(rest);
    }