What does Java's type parameter wildcard really mean? What's the real difference between Foo and Foo<?>?

后端 未结 5 995
清酒与你
清酒与你 2021-01-05 02:32

For a generic interface:

public interface Foo {
    void f(T t); 
} 

The difference between the two fields:

publ         


        
5条回答
  •  耶瑟儿~
    2021-01-05 02:48

    The wildcard in Foo indicates that within the current scope, you don't know or care what type of 'Foo' you have.

    Foo and Foo are the same (the first is shorthand for the other). Foo is different.

    A concrete example:

    You can assign any sort of List to List e.g.

    List list1 = new ArrayList();
    List list2 = new ArrayList();
    List list3 = new ArrayList();
    
    
    

    If you have a List you can call size() because you don't need to know what type of list it is to find out its size. And you can call get(i) because we know that the list contains some sort of Object, so the compiler will treat it as if get returns and Object.
    But you can't call add(o) because you don't know (and the compiler doesn't know) what sort of list you're dealing with.
    In our example above you wouldn't want to allow list1.add(new Object()); because that's supposed to be a list of Strings

    The reason for wildcards is so you can do things like this:

    public static boolean containsNull(List list)
    {
        for(Object o : list )
        {
           if( o == null ) return true;
        }
        return false;
    }
    

    That code can work on any sort of list that you want, a List, List, List, etc.

    If the signature was public static boolean containsNull(List list) then you could only pass List to it, List wouldn't work.

    提交回复
    热议问题