When to use generic methods and when to use wild-card?

前端 未结 9 2385
猫巷女王i
猫巷女王i 2020-11-22 10:32

I am reading about generic methods from OracleDocGenericMethod. I am pretty confused about the comparison when it says when to use wild-card and when to use generic methods.

9条回答
  •  天命终不由人
    2020-11-22 10:48

    Mainly -> Wildcards enforce generics at the parameter/argument level of a Non-Generic method. Note. It can also be performed in genericMethod by default, but here instead of ? we can use T itself.

    package generics;

    public class DemoWildCard {
    
    
        public static void main(String[] args) {
            DemoWildCard obj = new DemoWildCard();
    
            obj.display(new Person());
            obj.display(new Person());
    
        }
    
        void display(Person person) {
            //allows person of Integer,String or anything
            //This cannnot be done if we use T, because in that case we have to make this method itself generic
            System.out.println(person);
        }
    
    }
    
    class Person{
    
    }
    

    SO wildcard has its specific usecases like this.

提交回复
热议问题