gpt4 book ai didi

java - 在 JAVA 中解释这种泛型行为

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:05:41 24 4
gpt4 key购买 nike

public class MyList<Item> implements Iterable<Item> {
Node<Item> first;
int n = 0;

private static class Node<Item>
{
private Item item;
private Node<Item> next;
}
public Iterator<Item> iterator() {
return new ListIterator<Item>();
}

private class ListIterator<Item> implements Iterator<Item> // parameter Item is hiding the type Item
{
private Node<Item> current = first; // This does not compile

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

public Item next() {
Item item = current.item;
current = current.next;
return current.item;
}
}
...
}

我得到的错误是

"Type Mismatch : can't convert from MyList.Node to MyList.Node".

不确定这是否与警告有关

"paramter Item is hiding the type item"

如果我收到 private class ListIterator<Item> implements Iterator<Item> 的警告,为什么我没有收到 public class MyList<Item> implements Iterable<Item> 的警告? ?

最佳答案

如果内部类 ListIterator 的泛型类型参数应该与封闭类 MyList 的类型参数相同,则不应声明两次。

将内部类更改为:

private class ListIterator implements Iterator<Item>

这样,firstcurrent 的类型将相同。

正如 Michael 评论的那样,您必须将 ListIterator 实例的构造更改为:

public Iterator<Item> iterator()  {
return new ListIterator();
}

关于java - 在 JAVA 中解释这种泛型行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51135165/

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