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 ...
随机推荐
- IT人的自我导向型学习:学习的3个维度
看到大家对我的文章赞了不少,看来大家还比较喜欢看.园子里的一些朋友和我说:”终于又看到你要在园子里发原创文章了.几年前就受益匪浅,经过几年的成长分享来的东西肯定也是精品.“ 感谢大家对我的信任,如果你 ...
- 说说jsonp
什么是jsonp jsonp充其量只能说是一种"方法".它可以让页面从其他域中获取资料. 首先要知道的是同源策略,在javascript中使用http请求(ajax)是会受到同 ...
- Python+Selenium进行UI自动化测试项目中,常用的小技巧2:读取配置文件(configparser,.ini文件)
在自动化测试项目中,可能会碰到一些经常使用的但 很少变化的配置信息,下面就来介绍使用configparser来读取配置信息config.ini 读取的信息(config.ini)如下: [config ...
- [Solution] ASP.NET Identity(2) 空的项目使用
在本节中,我将说明将ASP.NET Identity添加到现有的项目或者一个空项目.我将介绍你需要添加的Nuget和Class.此示例中,会使用LocalDB. 本节目录: 注册用户 登入登出 注册用 ...
- Ubuntu搭建Android交叉编译环境
一.下载 Android NDK Android NDK官方下载页:http://developer.android.com/tools/sdk/ndk/index.html如果需要旧版本的,比如10 ...
- ASP.NET MVC使用input标签上传文件
有些时间学习了,温习一下ASP.NET MVC了.上传文档是在开发过程中,必须撑握的一个功能.以前上传均是使用第三方控件uploadify来实现,今天使使用VS标准标签input 的type=&quo ...
- Netty学习之客户端创建
一.客户端开发时序图 图片来源:Netty权威指南(第2版) 二.Netty客户端开发步骤 使用Netty进行客户端开发主要有以下几个步骤: 1.用户线程创建Bootstrap Bootstrap b ...
- 51Node 1364--- 最大字典序排列(树状数组)
51Node 1364--- 最大字典序排列(树状数组) 1364 最大字典序排列 基准时间限制:1 秒 空间限制:131072 KB 分值: 80 难度:5级算法题 收藏 关注 给出一个1至N ...
- 由简入繁实现Jquery树状结构
在项目中,我们经常会需要一些树状结构的样式来显示层级结构等,比如下图的样式,之前在学.net的时候可以直接拖个服务端控件过来直接使用非常方便.但是利用Jquery的一些插件,也是可以实现这些效果的,比 ...
- Visual Studio 2013 Preview 新功能
先来看一下Visual Studio的版本历史: 1. Visual Studio.NET 2002 2. Visual Studio.NET 2003 3. Visual Studio.NET 20 ...