Difference between Bounded Type parameter (T extends) and Upper Bound Wildcard (? extends)

后端 未结 5 1074
余生分开走
余生分开走 2020-12-16 14:18

I know that there was a similar question already posted, although I think mine is somewhat different...

Suppose you have two methods:

// Bounded type         


        
5条回答
  •  执笔经年
    2020-12-16 14:58

    I can think of the below differences :

    a) Modifying your list inside the method, consider below code :

    private static void processList(List someList)
    {
    
    
       T t = someList.get(0);
       if ( t.getClass() == Integer.class )
       {
           Integer myNum = new Integer(4);
           someList.add((T) myNum);
       }
    
    }
    
    // Upper bound wildcard
    private static void processList2(List someList)
    {
        Object o = someList.get(0);
        if ( o instanceof Integer )
        {
            Integer myNum = new Integer(4);
            someList.add(myNum); // Compile time error !!
        }
    }
    

    With wildcard you cannot add elements to the list ! Compiler tells you that it doesn't know what is myNum. But in the first method, you could add a Integer by first checking if T is Integer , no compile time error.

    b) The first method is called generic method. It follows the syntax that is defined for a generic method. The upper bounds specified in the method definition are used to restrict the parameter types.

    The second one is NOT necessarily called a generic method, it is a normal method that happens to accept a generic parameter. The wildcard ? with extends keyword is used as a means of relaxing the types that the method can accept.

提交回复
热议问题