`
leonzhx
  • 浏览: 768238 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

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<Type1> is neither a subtype nor a supertype of List<Type2>.

 

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<E>[], new List<String>[], 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<String> to an array of List<Integer> at runtime.

 

5.  Types such as E, List<E>, and List<String> 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.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics