简体   繁体   中英

Passing an array to a method in JAVA

I have a problem with this code. When I call the method sort and pass an array as a parameter to it (sort(array)), it is giving me an error. Can someone please tell what is wrong? Thanks

public class MergeSort {

public static <T extends Comparable<T>> void sort (T[] a) {
    if (a.length <= 1) 
        return;

    int hSize = a.length / 2;

    T[] lTab = (T[])new Comparable[hSize];
    T[] rTab = (T[])new Comparable[a.length-hSize];

    System.arraycopy(a, 0, lTab, 0, hSize);
    System.arraycopy(a, hSize, rTab, 0,a.length-hSize);

    sort(lTab); 
    sort(rTab);
    merge(a, lTab, rTab);
}

private static <T extends Comparable<T>> void merge (T[] a, T[] l, T[] r) {
    int i = 0;  // indexes l
    int j = 0;  // indexes r
    int k = 0;  // indexes a

    while (i < l.length && j < r.length)
        if (l[i].compareTo(r[j]) < 0)
            a[k++] = l[i++];
        else
            a[k++] = r[j++];

    while (i < l.length) 
        a[k++] = l[i++];

    while (j < r.length) 
        a[k++] = r[j++];
    }

}

The error is:

method sort in class MergeSort cannot be applied to given types Required T[] Found int[]

You have to make sure the type provided indeed implements Comparable

It seems you are passing int[] instead of Integer[]

You will not be able to use primitive types. For those cases, you will have to use their Wrappers which inherently implement Comparable.

If you are using your own type (ie your own Object) then that type must implement Comparable.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM