Effective Java 25 Prefer lists to arrays
Difference |
Arrays |
Lists |
1 |
Covariant |
Invariant |
2 |
Reified at runtime |
Erased at run time |
3 |
Runtime type safety |
Compile time type safety |
non-reifiable types |
E, List<E> and List<String> |
whose runtime representation contains less information than its compile-time representation. |
Reifiable types |
List<?> and Map<?,?> |
Reverse to above. |
This code fragment is legal:
// Fails at runtime!
Object[] objectArray = new Long[1];
objectArray[0] = "I don't fit in"; // Throws ArrayStoreException
but this one is not:
// Won't compile!
List<Object> ol = new ArrayList<Long>(); // Incompatible types
ol.add("I don't fit in");
Prohibition on generic array creation
- Not possible for a generic type to return an array of its element type.
- Not possible for using varargs methods in combination with generic types.( This is because every time you invoke a varargs method, an array is created to hold the varargs parameters. Use warning suppress to deal with it if it's required.).
None of these array creation expressions are legal:
new List<E>[],
new List<String>[] ,
new E[].
All will result in generic array creation errors at compile time.
// Why generic array creation is illegal - won't compile!
List<String>[] stringLists = new List<String>[1]; // (1)
List<Integer> intList = Arrays.asList(42); // (2)
Object[] objects = stringLists; // (3)
objects[0] = intList; // (4)
String s = stringLists[0].get(0); // (5)
Let's pretend that line 1, which creates a generic array, is legal. Line 2 creates and initializes a List<Integer>containing a single element. Line 3 stores the List<String>array into an Object array variable, which is legal because arrays are covariant. Line 4 stores the List<Integer>into the sole element of the Object array, which succeeds because generics are implemented by erasure: the runtime type of a List<Integer>instance is simply List, and the runtime type of aList<String>[]instance is List[], so this assignment doesn't generate an ArrayStoreException. Now we're in trouble. We've stored a List<Integer> instance into an array that is declared to hold only List<String>instances. In line 5, we retrieve the sole element from the sole list in this array. The compiler automatically casts the retrieved element to String, but it's an Integer, so we get a ClassCastExceptionat runtime. In order to prevent this from happening, line 1 (which creates a generic array) generates a compile-time error.
Use the Lists instead of the array to check the type safety at compile time
// List-based generic reduction
static <E> E reduce(List<E> list, Function<E> f, E initVal) {
List<E> snapshot;
synchronized(list) {
snapshot = new ArrayList<E>(list);
}
E result = initVal;
for (E e : snapshot)
result = f.apply(result, e);
return result;
}
Summary
If you find yourself mixing them and getting compile-time errors or warnings, your first impulse should be to replace the arrays with lists.
Effective Java 25 Prefer lists to arrays的更多相关文章
- Effective Java 53 Prefer interfaces to reflection
Disadvantage of reflection You lose all the benefits of compile-time type checking, including except ...
- Effective Java 69 Prefer concurrency utilities to wait and notify
Principle Use the higher-level concurrency utilities instead of wait and notify for easiness. Use Co ...
- Effective Java 35 Prefer annotations to naming patterns
Disadvantages of naming patterns Typographical errors may result in silent failures. There is no way ...
- Effective Java 46 Prefer for-each loops to traditional for loops
Prior to release 1.5, this was the preferred idiom for iterating over a collection: // No longer the ...
- Effective Java 68 Prefer executors and tasks to threads
Principle The general mechanism for executing tasks is the executor service. If you think in terms o ...
- Effective Java 18 Prefer interfaces to abstract classes
Feature Interface Abstract class Defining a type that permits multiple implementations Y Y Permitted ...
- Effective Java 20 Prefer class hierarchies to tagged classes
Disadvantage of tagged classes 1. Verbose (each instance has unnecessary irrelevant fields). 2. Erro ...
- Effective Java 49 Prefer primitive types to boxed primitives
No. Primitives Boxed Primitives 1 Have their own values Have identities distinct from their values 2 ...
- Effective Java Index
Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...
随机推荐
- ok6410 android driver(8)
In the past, we know how to create and run a simple character device driver on pc, goldfish and ok64 ...
- dp - 2015 Multi-University Training Contest 2 1004 Delicious Apples
Delicious Apples Problem's Link: http://acm.hdu.edu.cn/showproblem.php?pid=5303 Mean: 一条长为L的环形路上种着n棵 ...
- 重构第18天 用条件语句来代替异常(Replace exception with conditional)
理解:本文中的“使用条件判断代替异常”是指把没有必要使用异常做判断的条件尽量改为条件判断. 详解: 重构前代码: public class Microwave { private IMicrowave ...
- .Net 自定义应用程序配置
.Net 自定义应用程序配置 引言 几乎所有的应用程序都离不开配置,有时候我们会将配置信息存在数据库中(例如大家可能常会见到名为Config这样的表):更多时候,我们会将配置写在Web.config或 ...
- 微软modern.IE网站,多版本IE免费测试工具集
微软今天发布了modern.IE,这是一系列免费的.针对Web 开发者的测试工具和资源集合网站,微软希望以此来帮助开发者更轻松地实现跨 IE 和其他现代浏览器.跨设备的兼容性,其他还有代码检测工具.标 ...
- bootstrap - table
http://bootstrap-table.wenzhixin.net.cn/zh-cn/documentation/
- 修改RectTransform的值
用uGUI的时候.经常需要动态改变RectTransform的值,
- 【转】 StringUtils中 isNotEmpty 和isNotBlank的区别
[转自]http://blog.csdn.net/foamflower/article/details/5713604 isNotEmpty将空格也作为参数,isNotBlank则排除空格参数 Str ...
- 【Asphyre引擎】发布了新版本V101
引擎简称还是PXL,但是这个P是Platform而不是Pascal. 修复了一些bug,增加了轻量级的随机数发生器,进一步完善了XML的解析. 不是很明白,为何把Pascal扩展库改成Platform ...
- Ahjesus获取自定义属性Attribute或属性的名称
1:设置自己的自定义属性 public class NameAttribute:Attribute { private string _description; public NameAttribut ...