简体   繁体   中英

Why does the inner class complain about generic type?

I have a class that implements Iterable so that the user can use an iterator. I'm using generics to allow the user to use any type and work with the class.

This is the working code below 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 the ListIterator defined like this-

private class ListIterator<Type> implements Iterator<Type>

I get 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 have to do that in order for me to be able to use Type inside my class? I added Type when defining CustomStackUsingArray and that works fine.

When you say class Something<T> (possibly with more than one type parameter), you're telling the compiler that you're defining a new generic class, with T as its parameter. You could have said private class ListIterator<Type2> implements Iterator<Type2> ; that would have been legal, but not what you want. It would have created a new generic class, where Type2 refers to the name of the new type parameter. When you say private class ListIterator<Type> implements Iterator<Type> , you're actually doing the exact same thing, but with the type parameter named Type instead of Type2 . This Type has no connection to the Type of the outer class. Also, inside this new class, whenever you say Type , you are referring to the new type parameter, which means you can no longer refer to the outer type parameter--it's hidden, which is what Eclipse is telling you.

This all happens because you told the compiler you wanted to create a new generic class. But you really don't. You just want an inner class that is part of the outer generic class you're defining (I think). Therefore, you need to leave off the first <Type> . And it should work the way you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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