未经检查的投射问题

时间:2010-11-06 17:24:33

标签: java casting

嘿,我正在尝试实现ShellSort算法,现在我遇到了一个问题:

warning: [unchecked] unchecked cast
found : java.util.Vector
required: java.util.Vector<java.lang.Object>
Vector<Object> vcur = (Vector<Object>)currentCols[tcur];
vtmp相同。

我不知道问题出在哪里。如果你能帮助我真的很棒。 :)
这是我的代码:

public static Vector<Object> shellSort(Vector<Object> ul) {
    int lcount = ul.size();
    int colcount = 4; // 2^x
    Vector[] currentCols = { ul };
    for(; colcount > 0; colcount = (colcount / 2)) {
        Vector[] tmpCols = new Vector[colcount];
        for(int t1 = 0; t1 < colcount; t1++) {
            tmpCols[t1] = new Vector<Object>();
        }
        int tcur = 0;
        int tcurlvl = 0;
        int ttmp = 0;
        for(int t2 = 0; t2 < lcount; t2++) {
            Vector<Object> vcur = (Vector<Object>)currentCols[tcur];
            Vector<Object> vtmp = (Vector<Object>)tmpCols[ttmp];
            vtmp.addElement((Object)vcur.elementAt(tcurlvl));

            // step to next place
            tcur++;
            ttmp++;
            if(tcur == currentCols.length) { tcur = 0; tcurlvl++; }
            if(ttmp == tmpCols.length) { ttmp = 0; }
        }
    }
    return ul;
}

3 个答案:

答案 0 :(得分:1)

我认为这里的问题是类型擦除。在运行时,Vector就是Vector。例如:

Vector<String> stuff = new Vector<String>()
Vector<Object> objects = (Vector<Object>)stuff

它会编译,但在尝试将Int放入对象时会在运行时失败。

答案 1 :(得分:1)

这仍然无法解决问题(你的代码不起作用......永远不会排序)但它更新为使用List而不是Vector(Vector已经过时,因为官方API依赖它而不能弃用)。除非您需要内置到Vector中的同步,否则使用List / ArrayList。

我还将数组创建更改为更接近泛型(不能真正做通用数组创建)。

最后,我将整个方法设为通用的,这样它就可以安全地使用Object以外的东西(如List或List等)。

但它仍然会发出警告。也许你应该努力让代码在你担心这个特殊的警告之前正常工作(通常我不建议这样做,但是使用泛型有时可能是更好的方法)。

public static <T> List<T> shellSort(List<T> ul) 
{
    int lcount = ul.size();
    int colcount = 4; // 2^x

    List<T>[] currentCols = (List<T>[])Array.newInstance(List.class, 1);
    currentCols[0] = ul;

    for(; colcount > 0; colcount = (colcount / 2))
    {
        List<T>[] tmpCols = (List<T>[])Array.newInstance(List.class, colcount);

        for(int t1 = 0; t1 < colcount; t1++)
        {
            tmpCols[t1] = new ArrayList<T>();
        }

        int tcur = 0;
        int tcurlvl = 0;
        int ttmp = 0;

        for(int t2 = 0; t2 < lcount; t2++)
        {
            List<T> vcur = currentCols[tcur];
            List<T> vtmp = tmpCols[ttmp];
            vtmp.add(vcur.get(tcurlvl));

            // step to next place
            tcur++;
            ttmp++;
            if(tcur == currentCols.length) { tcur = 0; tcurlvl++; }
            if(ttmp == tmpCols.length) { ttmp = 0; }
        }
    }

    return ul;
}

答案 2 :(得分:0)

你为什么宣布currentCols

Vector[] currentCols = { ul };

此数组始终包含一个元素 - ul。只需将currentCols[..]替换为ul,错误也会消失。