Why is the inner class complaining about the generic type?
I have a class that implements Iterable so that the user can use the iterator. I use generics to allow the user to use any type and work with the class.
Following is the working code without warnings -
public class CustomStackUsingArray<Type> implements CustomList<Type>, Iterable<Type> {
Type []arr;
public Iterator<Type> iterator() {
return (new ListIterator());
}
private class ListIterator implements Iterator<Type>{
//Implement Iterator here
}
//Implement other methods here
}
However, if I have a ListIterator defined like this:
private class ListIterator<Type> implements Iterator<Type>
I am getting a warning in Eclipse, The parameter Type is hiding the type Type
Why does it complain when I specify the generic type after my class? Shouldn't I be doing this so that I can use Type inside my class? I added Type
when defining CustomStackUsingArray
and it works great.
source to share
When you say class Something<T>
(possibly with multiple type parameters) you are telling the compiler that you are defining a new generic class, and T
its a parameter. You might say private class ListIterator<Type2> implements Iterator<Type2>
; that would be legal, but not what you want. He created a new generic class where it Type2
refers to the name of the new type parameter. When you say private class ListIterator<Type> implements Iterator<Type>
you are actually doing the same thing, but with a type parameter Type
instead Type2
. This Type
one has nothing to do with the Type
outer class. Also, in this new class, when you say Type
you are referencing a new type parameter, which means you can no longer refer to an external type parameter - it is hidden, which is what Eclipse says.
This is all happening because you told the compiler that you want to create a new generic class. But you really don't. You just need an inner class that is part of the outer generic class that you are defining (I think). Therefore, you need to leave the first one <Type>
. And it should work the way you want it to.
source to share