0

我遇到了未经检查的演员表的警告。我不确定如何解决这些警告。

编译器错误似乎选择list = (E[]) new IntKeyed [size];
了我们假设使用字母对字母的代码。
我们正在尝试使用泛型,因此使用“E”。

所以我想我一定在这段代码的某个地方搞砸了。当我查看错误时,它似乎处理了,但据我所知ArrayLists,我没有使用 an 。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
4

2 回答 2

1

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

应该是这样的:

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

如果您认为您的演员表应该起作用 - 添加@SuppressWarnings("unchecked")方法或语句级别(较小的范围更好)。编译器不会发出任何消息,但如果您的转换错误,您仍然会在运行时收到异常。

于 2013-10-15T09:12:40.603 回答
1

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

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

于 2013-10-15T09:15:28.130 回答