Item 25: Prefer lists to arrays

阅读更多

1.  Arrays are covariant which means simply that if Sub is a subtype of Super, then the array type Sub[] is a subtype of Super[]. Generics, by contrast, are invariant: for any two distinct types Type1 and Type2, List is neither a subtype nor a supertype of List.

 

2.  You can’t put a String into a Long container, but with an array you find out that you’ve made a mistake at runtime; with a list, you find out at compile time.

 

3.  Arrays are reified which means that arrays know and enforce their element types at runtime. If you try to store a String into an array of Long, you’ll get an ArrayStoreException. Generics, by contrast, are implemented by erasure. This means that they enforce their type constraints only at compile time and discard (or erase) their element type information at runtime.

 

4.  It is illegal to create an array of a generic type, a parameterized type, or a type parameter: new List[], new List[], new E[]. If they were legal, casts generated by the compiler in an otherwise correct program could fail at runtime with a ClassCastException. For example, due to erasure, it’s allowed to put an instance of List to an array of List at runtime.

 

5.  Types such as E, List, and List are technically known as nonreifiable types. Intuitively speaking, a non-reifiable type is one whose runtime representation contains less information than its compile-time representation. The only parameterized types that are reifiable are unbounded wildcard types such as List and Map. It is legal to create arrays of unbounded wildcard types.

 

6.  Every time you invoke a varargs method, an array is created to hold the varargs parameters. If the element type of this array is not reifiable, you get a warning. There is little you can do about these warnings other than to suppress them.

你可能感兴趣的:(Array,Generics,Covariant,reifiable)