Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

java - Errors occur when calling print(List<T> a, T b) with different T class

I am trying to learn Java Generics, and found the following code.

public static <T> void print(T a, T b){
    System.out.println(a);
    System.out.println(b);
}

public static void main(String[] args){
    print(new ArrayList<String>(), 1);
}

Which works with no problem.

However when I change print method to the following, it gives me compiling errors.

public static <T> void print(List<T> a, T b){
    System.out.println(a);
    System.out.println(b);
}

Error:

GenericTest.java:9: error: method print in class GenericTest cannot be applied to given types;
  print(new ArrayList<String>(), 1);
    ^
  required: List<T>,T
  found: ArrayList<String>,int
  reason: no instance(s) of type variable(s) T exist so that argument type int conforms to formal parameter type T
  where T is a type-variable:
    T extends Object declared in method <T>print(List<T>,T)
1 error

Can anyone help me understand the errors?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The first thing you should understand is that, with the following method signature

public static <T> void print(T a, T b)

Both T must be the same type, that is to say both a and b will have the same infered type.

So why does it work for new ArrayList<String>() and 1? Because both parameters can actually be represented as Serializable, which is the nearest common super type of ArrayList and Integer:

  • ArrayList implements the Serializable interface.
  • 1 can be boxed into an Integer, which is also Serializable.

So in this case, the compiler will infer T as Serializable.


In the second case, with the signature

public static <T> void print(List<T> a, T b)

There is no common super type T that would be valid for both List<String> and Integer. It is true that both String and Integer are Serializable, but since generics aren't polymorphic, it doesn't work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...