1
public static void main(String args[]) {
    List<Double> doubleList = new ArrayList<>();
    doubleList.add(new Double(101.215D));
    doubleList.add(new Double(102.215D));
    doubleList.add(new Double(103.215D));

    printIntValue1(doubleList);
    System.out.println("*******");
    printIntValue2(doubleList);
}


//bounded parameter
public static <T extends Number> void printIntValue1(List<T> list){
    for(T num : list){
        System.out.println(num.intValue());
    }
}
//Wildcard parametr
public static  void printIntValue2(List<? extends Number> list){
    for(Number num : list){
        System.out.println(num.intValue());
    }
}

As in above two methods, both gives same results. Can anybody tell me if all the work already done by bounded type then why the concept of wildcard is there? Does wildcard do some other work that bounded types don't?

  • in Java, generics only give you compile-time safety & checking, nothing more. in 1st case, you have a `T` that you can use to denote you specific type, in 2nd you don't; that's all. –  Nov 08 '16 at 11:58

1 Answers1

1

I think that from the perspective of your example, there is little benefit to be gained from using wildcards. I believe, however, that wildcards were introduced to support assignments (or related constructs) of generic types using related type parameters.

Consider:

List<Number> numberList = new ArrayList<Double>(); //Won't compile

Contrast that to:

List<? extends Number> anyNumberList = null;
anyNumberList = new ArrayList<Double>();
anyNumberList = new ArrayList<Integer>();

The second snippet is valid code.

I agree that, when seen from a method parameter type perspective, the wildcard type doesn't present considerably particular advantages.

ernest_k
  • 44,416
  • 5
  • 53
  • 99