在Java中使用泛型时强制转换

Min*_*ina 5 java generics casting

我编写了自己的Stack类(相关代码见下文).在next()-方法我不得不投current.itemItem,但我不知道为什么.current.item应该已经是的类型,Item因此铸造不应该是必要的 - 但如果我不投,它会出错.

public class Stack<Item> implements Iterable<Item> {

  private class Node {
      Item item;
      Node next;
  }

  private Node first= null;

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

  private class StackIterator<Item> implements Iterator<Item> {
    private Node current = first;

    public Item next(){
        Item item = (Item)current.item;
        current = current.next;
        return item;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Con*_*nos 7

您正在使用<Item>的两个类型参数StackStackIterator,而你真正想要做的是有StackIterator没有一个参数,只是表明它实现了Iterator<Item>:

    private class StackIterator implements Iterator<Item> {
        private Node current = first;

        @Override
        public Item next() {
            Item item = current.item; // no need to cast now
            current = current.next;
            return item;
        }
    }
Run Code Online (Sandbox Code Playgroud)


Kon*_*kov 7

类型参数StackIterator<Item>隐藏类型Item,该类型在Stack<Item>类的定义中引入.

这就是你需要进行演员(或添加@SuppressWarnings("hiding")注释)的原因.

为了摆脱警告,只需删除重复的类型:

private class StackIterator implements Iterator<Item> {

}
Run Code Online (Sandbox Code Playgroud)