Difference between Enumeration<? extends ZipEntry> and Enumeration?

后端 未结 3 1438
青春惊慌失措
青春惊慌失措 2021-01-02 06:19

Is there a difference between Enumeration and Enumeration? If so, what is the difference?

3条回答
  •  再見小時候
    2021-01-02 07:01

    There's no practical difference in terms of what you can do when you've got one of them, because the type parameter is only used in an "output" position. On the other hand, there's a big difference in terms of what you can use as one of them.

    Suppose you had an Enumeration - you couldn't pass this to a method which took Enumeration as one of its arguments. You could pass it to a method taking Enumeration though.

    It's more interesting when you've got a type which uses the type parameter in both input and output positions - List being the most obvious example. Here are three examples of methods with variations on a parameter. In each case we'll try to get an item from the list, and add another one.

    // Very strict - only a genuine List will do
    public void Foo(List list)
    {
        T element = list.get(0); // Valid
        list.add(element); // Valid
    }
    
    // Lax in one way: allows any List that's a List of a type
    // derived from T.
    public void Foo(List list)
    {
        T element = list.get(0); // Valid
         // Invalid - this could be a list of a different type.
         // We don't want to add an Object to a List
        list.add(element);   
    }
    
    // Lax in the other way: allows any List that's a List of a type
    // upwards in T's inheritance hierarchy
    public void Foo(List list)
    {
        // Invalid - we could be asking a List for a String.
        T element = list.get(0);
        // Valid (assuming we get the element from somewhere)
        // the list must accept a new element of type T
        list.add(element);
    }
    
    
    

    For more details, read:

    • The Java language guide to generics
    • The Java generics tutorial (PDF)
    • The Java generics FAQ - particularly the section on wildcards

    提交回复
    热议问题