警告:[未选中]未经检查的强制转换。泛型

时间:2013-10-15 09:10:55

标签: java generics unchecked-cast

我遇到了未经检查的演员的警告。我不知道如何解决警告。

编译器错误似乎在list = (E[]) new IntKeyed [size];上选择 这是我们用来写信的代码 我们试图使用泛型,因此使用“E”。

所以我认为我必须在这段代码的某个地方搞砸了。 当我查找错误时,它似乎与ArrayLists有关,但我并没有使用ArrayList知识。

也许我应该ArrayLists?会改变那个修复警告吗?我的代码中也存在未完成异常处理的问题。但我认为这与Array问题是隔离的。

您可以找到的任何错误都有助于我找到正确的方向。感谢。

public abstract class MyArrayList<E> implements IntKeyed
{

private final int DEFCAP = 50;
private int origCap;
private int numElements;
private E[] list;

public MyArrayList()
{
    origCap = DEFCAP;
    list = (E[]) new IntKeyed [origCap];    *******Error Here
}

public MyArrayList( int size ) throws Exception
{
    size = DEFCAP;
    if( size > 0 )
    {
        list = (E[]) new IntKeyed [size];    *******Error Here
        origCap = size;
    }
    else
    {
        throw new ArrayStoreException();
        System.out.println("List size is invalid");
    }
    list = (E[]) new IntKeyed [size];         *******Error Here
}

private void enlarge ()
{
    E[] larger = (E[]) new IntKeyed [list.length + origCap]; *******Error Here
    for( int i = 0; i < list.length; i++)
    {
        larger[i] = list[i];
    }
    list = larger;
}

使用javac -Xlint:unchecked MyArrayList.java进行编译时 我明白了:

MyArrayList.java:29: warning: [unchecked] unchecked cast
    list = (E[]) new IntKeyed [origCap];
                 ^
required: E[]
found:    IntKeyed[]
where E is a type-variable:
E extends Object declared in class MyArrayList
MyArrayList.java:37: warning: [unchecked] unchecked cast
        list = (E[]) new IntKeyed [size];
                     ^
required: E[]
found:    IntKeyed[]
where E is a type-variable:
E extends Object declared in class MyArrayList
MyArrayList.java:45: warning: [unchecked] unchecked cast
    list = (E[]) new IntKeyed [size];
                 ^
 required: E[]
found:    IntKeyed[]
where E is a type-variable:
E extends Object declared in class MyArrayList
MyArrayList.java:117: warning: [unchecked] unchecked cast
    E[] larger = (E[]) new IntKeyed [list.length + origCap];
                       ^
required: E[]
found:    IntKeyed[]
where E is a type-variable:
E extends Object declared in class MyArrayList
MyArrayList.java:43: error: unreachable statement
        System.out.println("List size is invalid");
        ^
1 error
4 warnings

2 个答案:

答案 0 :(得分:1)

警告不是问题,抛出异常后问题是无法访问的语句。

它应该是这样的:

System.out.println("List size is invalid");
throw new ArrayStoreException();

如果您认为您的演员阵容应该有效 - 在方法或声明级别添加@SuppressWarnings("unchecked")(更小的范围更好)。编译器不会发出任何消息,但如果转换是错误的,你仍会在运行时获得异常。

答案 1 :(得分:1)

list = (E[]) new IntKeyed [origCap];处的警告实际上意味着通用E被硬编码为IntKeyed,因此无论您为E传递什么,您的list将始终保持类型IntKeyed

在您的情况下,通用使用似乎不适合,因为您已经为此目的实现了特定的接口。