gpt4 book ai didi

java - 警告 : [unchecked] unchecked cast. 泛型

转载 作者:行者123 更新时间:2023-12-02 06:38:39 28 4
gpt4 key购买 nike

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

编译器错误似乎出现在 list = (E[]) new IntKeyed [size];
这是我们应该逐个字母使用的代码。
我们正在尝试使用泛型,因此使用“E”。

所以我想我一定在这段代码的某个地方犯了错误。当我查找错误时,它似乎处理 ArrayLists,但据我所知,我没有使用 ArrayList

也许我应该是ArrayLists?改变这个可以修复警告吗?我的代码中还存在不完整的异常处理问题。但我认为这与数组问题无关。

您发现的任何错误都将帮助我指明正确的方向。谢谢。

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

最佳答案

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

应该是这样的:

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

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

关于java - 警告 : [unchecked] unchecked cast. 泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19377333/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com