gpt4 book ai didi

java - 创建和转换对象数组时出错

转载 作者:行者123 更新时间:2023-12-02 05:21:58 24 4
gpt4 key购买 nike

我正在尝试创建一个迭代器,在其中创建一个对象数组。我必须对它们进行类型转换,因为不允许创建泛型数组。

我收到运行时错误

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LRandomizedQueueList$Node;

迭代器的完整代码如下所示。我不知道我做错了什么。

   private class RandomizedQueueIterator implements Iterator<Item> {
private Node current = first;
private Node[] ca = (Node[])new Object[size()];
//private Node[] ca = new Node[size()];

private RandomizedQueueIterator() {
if (first == null) throw new NoSuchElementException();
for (int j = 0; j < size(); j++) {
ca[j] = current;
current = current.next;
}
StdRandom.shuffle(ca);
current = ca[0];
}

public boolean hasNext() { return current != null; }

public Item next() {
if (current == null) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
public void remove() {
throw new UnsupportedOperationException("This method is not supported");
}
}

感谢您对理解此错误的任何帮助。

最佳答案

用途:

private Node[] ca = new Node[size()];

创建数组时无需强制转换。您只需创建一个 Node 数组即可。

关于java - 创建和转换对象数组时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26448023/

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