简体   繁体   English

MergeSort实现上的ClassCastException

[英]ClassCastException on MergeSort implementation

I was implementing the MergeSort algorithm but I am always getting a ClassCastException while converting it from Object . 我正在实现MergeSort算法,但是从Object转换它时,总是会收到ClassCastException For comparing two values of K , I used the intValue method. 为了比较K两个值,我使用了intValue方法。 Is there any other way to compare them? 还有其他比较方式吗?

import java.util.Arrays;
public class MergeSort {
    private static <K extends Number> K[] sort(K[] s) {
        int n = s.length;
        if (n == 0 || n == 1)
            return null;
        int mid = n / 2;
        if (n % 2 == 0) {
            K[] s1 = (K[]) new Object[n / 2];
            K[] s2 = (K[]) new Object[n / 2];
            for (int i = 0; i < n / 2; i++) {
                s1[i] = s[i];
                s2[i] = s[i + n / 2];
            }
            return merge(sort(s1), sort(s2));
        } else {
            K[] s1 = (K[]) new Object[n / 2];
            K[] s2 = (K[]) new Object[n / 2 + 1];
            for (int i = 0; i < n / 2; i++) {
                s1[i] = s[i];
                s2[i] = s[i + n / 2];
            }
            s2[n / 2] = s[n - 1];
            return merge(sort(s1), sort(s2));
        }
    }

    private static <K extends Number> K[] merge(K[] s1,K[] s2){
        int ll, rl;
        ll = s1.length;
        rl = s2.length;
        K[] merge = (K[]) new Object[ll+rl];
        int i = 0, j = 0;
        while (i + j < ll + rl) {
            if (j == rl || (i < ll && (s1[i].intValue() < s2[j].intValue())))
                merge[i + j] = s1[i++];
            else
                merge[i + j] = s1[j++];
        }
        return merge;
    }
}

Regarding the exception: 关于例外:

You are creating arrays of Object in your sort method which you then cast to K . 您正在用sort方法创建Object数组,然后将其强制转换为K。

But casting an array like this doesn't magically turn objects into K instances. 但是,像这样强制转换数组并不能将对象神奇地变成K个实例。 Your whole idea how to use generics here doesn't make sense. 您在这里如何使用泛型的整个想法没有任何意义。 Try implementing your sort for arrays of Number first. 首先尝试对Number数组实现排序。

And: normally you would create these "temp" arrays only in the merge step. 并且:通常,您只会在合并步骤中创建这些“临时”数组。 Also having temp arrays for the first partitioning of data looks suspiciously like waste of memory. 同样具有用于第一次数据分区的临时数组看起来也像浪费内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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