简体   繁体   English

Java Generics不兼容的类型linkedlist迭代器

[英]Java Generics incompatible types linkedlist iterators

Trying to create an iterator for a generic linked list. 尝试为通用链表创建迭代器。 When I attempt to create a 'current' node for the purpose of iterating through the list based upon the head sentinel, I get an incompatible type error. 当我尝试创建一个“当前”节点以便根据头部标记迭代列表时,我得到一个不兼容的类型错误。 Here's the relveant lines 这是重要的线条

public class LinkedList<T> implements Iterable<T>
{
    private node<T> headsent;
    private node<T> tailsent; 
    public DistanceEventList()
    {
        headsent = new node<T>();
        tailsent = new node<T>();
        headsent.setnext(tailsent);
        tailsent.setprevious(headsent);
    }
    public node<T> getheadsent()
    {
        return headsent;
    }
    ...
    public MyIterator<T> iterator() {
        return new MyIterator<T>();
    }
    public class MyIterator<T> implements Iterator<T>
    {
        private node<T> current = getheadsent();
        public T next() {
            current = current.getnext();
            return current.getdata();
        }
    private class node<T> {
        private T data;
        private node<T> next;
        private node<T> previous;    
        ...
        public node<T> getnext()
        {
            return next;
        }
    }
}

And the error produced 并产生错误

LinkedList.java:65: error: incompatible types
private node<T> current = getheadsent();
required: LinkedList<T#1>.node<T#2)
found: LinkedList<T#1>.node<T#1)

Seems like I've introduced two different types of T, but I'm not very experienced with generics to know for sure. 好像我已经介绍了两种不同类型的T,但我对于通用的确不太熟悉。 Hopefully the code above is enough for someone to identify the error (it's quite gutted). 希望上面的代码足以让某人识别出错误(它已经过时了)。 Thanks! 谢谢!

You have two types with the same name. 您有两种名称相同的类型。

Inner classes share type variables that are declared in their outer class. 内部类共享在其外部类中声明的类型变量。 So when you have 所以,当你有

public class MyIterator<T> implements Iterator<T>
//                     ^^^

The new type declaration <T> shadows the outer one. 新类型声明<T>遮蔽外部声明。

private node<T> current = getheadsent();
//      ^^^^^^^           ^^^^^^^^^^^
//      inner T             outer T

You can just remove the declaration: 你可以删除声明:

public class MyIterator implements Iterator<T>
//                    ^^^

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM