I am having trouble sending my arraylist as a param to a generic method. Any idea what im doing wrong here?
ArrayList<Integer> list50k = new ArrayList<>();
list50k.add(1);
list50k.add(5);
list50k.add(8);
list50k.add(7);
selectionSort(list50k); // error is in this line
I then try to send the array to the method and get an error. here is the method:
public static <T extends Comparable<T>> void selectionSort(T[] list){...}
The problem is that ArrayList<T>
is not an array, meaning it can't be converted to a T[]
.
Your method signature could be selectionSort(List<T>)
if you wanted to pass the ArrayList
.
You could also convert the ArrayList
to a T[]
but the syntax for that is a little annoying in java and I don't recommended unless you really need an array.
Try this one
selectionSort(list50k.toArray(new Integer[list50k.size()]));
get Integer[]
from ArrayList<Integer>
to make it valid argument as per your method signature.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.