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

前端 未结 9 2290
猫巷女王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:49

    ? means unknown

    The general rule applies: You can read from it, but not write

    given simple pojo Car

    class Car {
        void display(){
    
        }
    }
    

    This will compile

    private static  void addExtractedAgain1(List cars) {
        T t = cars.get(1);
        t.display();
        cars.add(t);
    }
    

    This method won't compile

    private static void addExtractedAgain2(List cars) {
        Car car = cars.get(1);
        car.display();
        cars.add(car); // will not compile
    }
    

    Another example

    List hi = Arrays.asList("Hi", new Exception(), 0);
    
    hi.forEach(o -> {
       o.toString() // it's ok to call Object methods and methods that don't need the contained type
    });
    
    hi.add(...) // nothing can be add here won't compile, we need to tell compiler what the data type is but we do not know
    

提交回复
热议问题