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 ...
随机推荐
- 2 Servlet基础
作者:禅楼望月(http://www.cnblogs.com/yaoyinglong) 1. 从浏览器访问Servlet的流程 刚才发现,这里的图片不能正常显示,所以我给个链接,大家可以下载下来看从浏 ...
- Angular系列----AngularJS入门教程02:静态模板(转载)
为了说明angularJS如何增强了标准HTML,我们先将创建一个静态HTML页面模板,然后把这个静态HTML页面模板转换成能动态显示的AngularJS模板. 在本步骤中,我们往HTML页面中添加两 ...
- iOS实现图像的反色,怀旧,色彩直方图效果
反色是与原色叠加可以变为白色的颜色,即用白色(RGB:1.0,1.0,1.0)减去原色的颜色.比如说红色(RGB:1.0,0,0)的反色是青色(0,1.0,1.0).在OPENGL ES中为1. 通过 ...
- 非聚集索引中的临界点(Tipping Point)
什么是临界点? 注意,我要说的问题是非聚集索引的执行计划从Seek+Lookup变成Table/Clustered Index Scan的临界点.SQL Server的访问数据的IO最小单元是页. 我 ...
- ok6410 android driver(11)
This essay, I go to a deeply studying to android HAL device driver program. According to the android ...
- Linq专题之Linq查询from子句
Linq查询表达式包含8个常用的子句:from.where.select.join.into.orderby.group.let.我们来看看详细的说明. from: 指定查询操作的 ...
- Unity Shader入门基础(一)
渲染流水线 一.渲染流水线 渲染流水线的工作任务在于由一个三维场景出发.生存(或者说渲染)一张二维图像.换句话说,计算机需要从一系列的顶点数据.纹理等信息出发,把这些信息最终转换成一张人眼可以看到 ...
- TCP和UDP之间的区别
TCP---传输控制协议,提供的是面向连接.可靠的字节流服务.当客户和服务器彼此交换数据前,必须先在双方之间建立一个TCP连接,之后才能传输数据.TCP提供超时重发,丢弃重复数据,检验数据,流量控制等 ...
- EF工作中踩过的坑.
1.EF同一个linq里边不支持两个或两个以上不同dbcontext的使用,必须拆解开才能使用; ef也不支持自定义集合和dbcontext属性的混合使用. 2.如果要用用统一域账号连接databas ...
- javascript: Jquery each loop with json array or object
http://www.codeproject.com/Articles/779303/JSON-and-Microsoft-technologies http://www.codeproject.co ...