Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does java infer serializable on passing the arraylist object of string to generic method

Tags:

java

  1. static <T> T pick(T a1, T a2) { return a2; }
  2. Serializable s = pick("d", new ArrayList<String>());

if I am making the reference to String or any other type. Compiler is throwing an error .

Could you please help me understand why does java infer it to Serializable?

like image 944
user35253 Avatar asked Jan 03 '23 00:01

user35253


1 Answers

  • As argument a1, you're passing "d" of type String.
  • As argument a2, you're passing new ArrayList<String>() of type ArrayList<String>

The nearest common supertype of String and ArrayList is Serializable. It would also work if you wrote:

Object s = pick("d", new ArrayList<String>());
like image 151
Erwin Bolwidt Avatar answered Jan 05 '23 14:01

Erwin Bolwidt