List cannot be converted to ArrayList

前端 未结 3 1781
迷失自我
迷失自我 2021-01-06 12:39

At the beginning of my code, there is:

List> result = new ArrayList();

And then, (here is to reverse a sub-list):

3条回答
  •  生来不讨喜
    2021-01-06 13:15

    You're using a specific implementation of the List interface as a return type for the reverse function (namely ArrayList). This forces what you return to be an ArrayList, but you're defining it as List.

    To understand, try and change the construction part to use a LinkedList, which also implements List:

    List newList = new LinkedList();
    

    This construction is valid, but now we try and return a LinkedList from a function that returns an ArrayList. This makes no sense since they aren't related (But notice this: they both implement List).

    So now you have two options:

    Make the implementation more specific by forcing use of ArrayLists:

    ArrayList newList = new ArrayList<>();
    

    Or better, make the implementation more general by changing the function's return type (any List can be plugged in):

    public List reverse(List list){
    

提交回复
热议问题