Java Generics Syntax for arrays

前端 未结 6 1626
梦谈多话
梦谈多话 2020-12-10 12:17

What data structure does the following declaration specify?

 List[] myArray;

I think it should declare an array where each

6条回答
  •  我在风中等你
    2020-12-10 13:09

    The answer is that arrays can only hold reified types. And generified classes are not reified. That is, the runtime "type" of the List is just List. Generics are erased at runtime (google "wall of erasure" for more).

    So this:

    List[] myArray
    

    really means:

    List[] myArray
    

    There is no type-safe way to declare what you're trying to declare. Generally, I'd recommend you use a List instead of an array in this case. Some people have gone so far as to suggest that arrays should be treated as deprecated types now that we have generics. I can't say I'm willing to go that far but you should consider whether a collection is a better alternative whenever you're drawn to an array.

    The book Java Generics and Collections by Naftalin and Wadler is an excellent reference for questions you might have about generics. Or, of course, the Generics FAQ is your canonical online reference.

提交回复
热议问题