I have been having this issue which I am not able to resolve at the moment. It is a type mismatch between List and ArrayList. I am not too sure of what went wrong with my work. Any help will be appreciated.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Test {
// Sum of array
static Integer sumArray(ArrayList<Integer> Array){
Integer sum=Integer.valueOf(0);
for(int i=0;i<Array.size();i ){
sum =Array.get(i);
}
return sum;
}
public static void main(String[] args){
ArrayList<Integer> RideArr = new ArrayList<Integer>(); // Initializing array
// Print out the RideArr values in list format(~)
RideArr.add(1);
RideArr.add(2);
RideArr.add(3);
RideArr.add(4);
RideArr.add(5);
ArrayList<Integer> jack=RideArr.subList(0, 4);
System.out.println(sumArray(jack));
}
}
Error: incompatible types: List cannot be converted to ArrayList ArrayList jack=RideArr.subList(0, 4);
CodePudding user response:
The type of a variable should pretty much never be ArrayList
. ArrayList is one specific kind of list implementation. someList.subList(a, b)
does not return an ArrayList. It returns a List just fine, it's just not exactly an arraylist. Even ArrayList's own subList does not, itself, return an ArrayList.
It shouldn't matter what the implementation is, hence, using ArrayList
anywhere is wrong; except with new ArrayList
, as you can't write new List
- with new
, that is the one time you need to tell java what kind of list implementation you want. Thus:
List<Integer> rideArr = new ArrayList<>();
List<Integer> jack = rideArr.subList(0, 4);
NB: We write TypesLikeThis
and variablesLikeThis
, so, rideArr
, not RideArr
.
CodePudding user response:
Try this one:
ArrayList<Integer> jack = new ArrayList<>(RideArr.subList(0,4));
System.out.println(sumArray(jack));