Generic Methods and Type Inferencing in Java

前端 未结 3 582
攒了一身酷
攒了一身酷 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<T> is an invariant whose value determines the type of the first parameter T.

    For instance, this is valid:

    fancy("", new ArrayList<CharSequence>()); //compiles Ok
    

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

    However, this is not valid:

    fancy((CharSequence)"", new ArrayList<String>()); //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.

    0 讨论(0)
  • 2021-02-06 05:22

    I guess you could say it serves as some sort of documentation, so that the user knows that you expect both arguments to be of the same type. Of course, any two objects are of the same type to some degree (they're all Object), so it's a meaningless statement.

    Long story short, it's a useless signature.

    Of course, if plain returned a type T, that'd be a different story.

    0 讨论(0)
  • 2021-02-06 05:24

    While the compiler does not infer the generic type one might intend, it will enforce type constraints that are explicitly specified. The following invocation results in a type error.

    this.<String>plain("", new ArrayList<Integer>()); /* Compiler error. */
    

    The parameterized method <String>plain(String, String) of type Test is not applicable for the arguments (String, ArrayList<Integer>)

    0 讨论(0)
提交回复
热议问题