Generic Methods and Type Inferencing in Java

前端 未结 3 577
攒了一身酷
攒了一身酷 2021-02-06 04:41

Given the following not-very-useful code:

package com.something;

import java.util.ArrayList;
import java.util.Collectio         


        
3条回答
  •  余生分开走
    2021-02-06 05:13

    The 2nd call to fancy() is a compiler error because Java can't infer any common type between the two arguments (can't infer Object since the second parameter must be a Collection.)

    Well, I am not sure this is the reason, I would say the reason is that the generic type T in Collection is an invariant whose value determines the type of the first parameter T.

    For instance, this is valid:

    fancy("", new ArrayList()); //compiles Ok
    

    Because all String are CharSequences. It is expected that the first parameter is a CharSequence once the type is inferred from ArraysList.

    However, this is not valid:

    fancy((CharSequence)"", new ArrayList()); //compiler error
    

    Because it is expected the type of the first parameter be String, and we cannot ensure that all CharSequences are, in fact, of type String, right?

    So, AFAIK, the reason the types are not compatible is due to the nature of generics in this case, and not to the fact that the second type is a Collection.

提交回复
热议问题