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 ...
随机推荐
- Android 学习笔记之Volley开源框架解析(三)
学习内容: 1.CacheDispatcher缓存请求调度... 2.Cache缓存数据的保存... 3.DiskBasedCache基于磁盘的缓存类实现方式... 前面说到使用Volley发 ...
- Python内置模块(2)
这一部分主要介绍sys.os.hashlib和re模块.其中的re模块介绍得非常详细,是本部分的重点! 均为python3.5.1环境. 一.sys模块 sys模块涉及的主要是与python解释器相关 ...
- C#函数式程序设计之代码即数据
自3.5版本以来,.NET以及微软的.NET语言开始支持表达式树.它们为这些语言的某个特定子集提供了eval形式的求值功能.考虑下面这个简单的Lambda表达式: Func<int, int, ...
- [Solution] 1分钟使用log4net
log4net库是Apache log4j框架在Microsoft .NET平台的实现,是一个帮助程序员将日志信息输出到各种目标(控制台.文件.数据库等)的工具 官网:http://logging.a ...
- MVC知识点02
MVC基础知识详情 1:在MVC中如果要从前台页面(.aspx)获取参数,只需要将其两个页面的参数设置成一样的,这样子MVC中的机制就会自动的将参数的值传到方法中. 2:在MVC中的方法要是两个都是相 ...
- JavaScrip的DOM操作
1.DOM的基本概念 DOM是文档对象模型,这种模型为树模型,文档是指标签文档:对象是指文档中每个元素:模型是指抽象化的东西 2.Windows对象操作 一.属性和方法 二.Window.open(& ...
- macbook装双系统多分区其实很简单,你只要把macbook当作一台普通pc就可以了!
macbook装双系统多分区其实很简单,你只要把macbook当作一台普通pc就可以了! 不用理会苹果官网的警告,苹果官网警告你只能用bootcamp安装且不能多分区,把人吓得不轻.其实不用过多担心, ...
- Dev 饼图
// 添加引用命名空间 using DevExpress.XtraCharts; /* *具体步骤:(1)先构建饼图对象的数据源DataTable * (2)再设置饼图对象的相关参数 * (3)饼图空 ...
- WebApi传参总动员(四)
前文介绍了Form Data 形式传参,本文介绍json传参. WebApi及Model: public class ValuesController : ApiController { [HttpP ...
- php中的字符串常用函数(四) ord() 获得字符的ascii码 chr()获取ascii码对应的字符
ord('a');//=>97 返回小写a 的ascii码值97 chr(97);//=>a 返回ascii码表上的97对应的 小写a