So, I have got a problem in my Main class when I would like to call the mergeSort() method caused by the Comparator. I get the following message:
I have no idea how to fix that issue.. please help me!
Notice: Don't wonder that there doesn't happen anything in the code. I got stuck because I cannot prove the functionality of my code because of the above described problem :(
(Sry for my bad english)
class Algorithms
{
public static <T> void mergeSort(final T[] a, final Comparator<T> c)
{
T[] list = a;
Comparator<T> comp = c;
}
}
public class Main
{
public static void main(String[] args)
{
int[] unsortedList = {4,5,7,1,98,32}; //Expected = 1,4,5,7,32,98
Comparator<Integer> sorted = Comparator.naturalOrder();
int[] sortedList = Algorithms.mergeSort(unsortedList,sorted))
}
}
In this code, the types don't match in the Algorithms.mergeSort
call:
int[] unsortedList = {4,5,7,1,98,32}; //Expected = 1,4,5,7,32,98 Comparator<Integer> sorted = Comparator.naturalOrder(); Algorithms.mergeSort(unsortedList, sorted))
The type of unsortedList
is int[]
and the type of sorted
is Comparator<Integer>
. To make the types match, you need to use Integer[]
as the type of unsortedList
:
Integer[] unsortedList = {4, 5, 7, 1, 98, 32}; //Expected = 1,4,5,7,32,98
Another problem is that Algorithms.mergeSort
returns void
, so this still won't compile:
int[] sortedList = Algorithms.mergeSort(unsortedList, sorted);
You need to drop the assignment:
Algorithms.mergeSort(unsortedList, sorted);
Putting it together, this will work (after you implement Algorithms.mergeSort
):
public static void main(String[] args) {
Integer[] unsortedList = {4, 5, 7, 1, 98, 32};
Comparator<Integer> sorted = Comparator.naturalOrder();
Algorithms.mergeSort(unsortedList, sorted);
}
使用Integer[]
而不是int[]
。
Another possibility would also be to work on a clone:
class Algorithm
{
public static <T> T[] mergeSort(final T[] a, final Comparator<T> c)
{
T[] list = a.clone();
Comparator<T> comp = c;
Arrays.sort(list, comp);
return list;
}
public static void main(String[] args)
{
Integer[] unsortedList = {4,5,7,1,98,32}; //Expected = 1,4,5,7,32,98
Comparator<Integer> sorted = Comparator.naturalOrder();
Integer[] sortedList = Algorithm.mergeSort(unsortedList,sorted);
}
}
If you just want things to compile, you can look at this. There were a few problems:
There were multiple syntax problems, like lack of semicolons and too many parens.
import java.util.Comparator; class Algorithms { public static <T> void mergeSort(final T[] a, final Comparator<T> c) { T[] list = a; Comparator<T> comp = c; } } public class Main { public static void main(String[] args) { Integer[] unsortedList = {4,5,7,1,98,32}; //Expected = 1,4,5,7,32,98 Comparator<Integer> sorted = Comparator.naturalOrder(); Algorithms.mergeSort(unsortedList,sorted); } }
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.