How is the datatype of type parameter decided in covariance and contravariance?

◇◆丶佛笑我妖孽 提交于 2019-12-05 08:24:40

T is decided based upon the arguments but can be specified explicitly as well. So, yes it can be Comparable and Serializable.

All of these are valid:

     Collections.<Number>copy(objs, ints);
     Collections.<Comparable>copy(objs, ints);
     Collections.<Serializable>copy(objs, ints);
     Collections.<Integer>copy(objs, ints);

     Collections.copy(objs, ints); // implicitly Integer

When no type is specified Integer is picked due to the way <? extends Integer> is handled and explained in java documentation

benmmurphy

http://docs.oracle.com/javase/specs/jls/se7/jls7.pdf

From the 'simple' example the JLS says it chooses the most specific type that satisfies all the constraints it generates.

15.12.2.7 Inferring Type Arguments Based on Actual Arguments

A supertype constraint T :> X implies that the solution is one of supertypes of X. Given several such constraints on T, we can intersect the sets of supertypes implied by each of the constraints, since the type parameter must be a member of all of them. We can then choose the most specific type that is in the intersection

Copy.java:11: incompatible types
found   : java.lang.Integer[]
required: java.lang.String[]
    String[] res = copy(Arrays.<Object>asList(2, 3.14, "four"), Arrays.asList(5, 6));
                       ^
1 error
➜  /tmp  cat Copy.java 
import java.util.*;
public class Copy {
public static <T> T[] copy(List<? super T> dst, List<? extends T> src) {
   for (int i = 0; i < src.size(); i++) {
      dst.set(i, src.get(i));
   }

   return null;
  }
  public static void main(String[] args) {
    String[] res = copy(Arrays.<Object>asList(2, 3.14, "four"), Arrays.asList(5, 6));
  }

}

Object class is the super type of Serializable and Comparable also
This is not true, Serializable and Comparable are interfaces and have no relation with Object.

Additionally the super ? is the exact inverse of extends ? which means it cannot be applied to interfaces. it can be applied to interfaces.

When you write ? extends T it means ? is an unknown subtype of T, probably T itself. I believe the JVM resolve T bottom up which means T is in fact Integer not Number(correct me if I am wrong).

Then

   Collections.copy(objs, ints)

is in fact

   Collections.<Integer>(objs, ints)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!