Java Generics Incompatible Types

Trying to create an iterator for a common linked list. When I try to create a "current" node for iteration through a list based on the main controller, I get an incompatible type error. Here are fascinating 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 an error occurred

 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) 

It looks like I introduced two different types of T, but I'm not very good at generics to know for sure. We hope that the code above is enough for someone to identify the error (it is quite gutted). Thanks!

+5
source share
1 answer

You have two types with the same name.

Inner classes share type variables declared in their outer class. Therefore when you have

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

A declaration of a new type <T> obscures the external.

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

You can simply delete the ad:

 public class MyIterator implements Iterator<T> // ^^^ 
+5
source

All Articles