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

  1. Not possible for a generic type to return an array of its element type.
  2. 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的更多相关文章

  1. Effective Java 53 Prefer interfaces to reflection

    Disadvantage of reflection You lose all the benefits of compile-time type checking, including except ...

  2. 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 ...

  3. Effective Java 35 Prefer annotations to naming patterns

    Disadvantages of naming patterns Typographical errors may result in silent failures. There is no way ...

  4. 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 ...

  5. 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 ...

  6. Effective Java 18 Prefer interfaces to abstract classes

    Feature Interface Abstract class Defining a type that permits multiple implementations Y Y Permitted ...

  7. Effective Java 20 Prefer class hierarchies to tagged classes

    Disadvantage of tagged classes 1. Verbose (each instance has unnecessary irrelevant fields). 2. Erro ...

  8. 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 ...

  9. 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 ...

随机推荐

  1. 小printf的故事(未完待续)

    小printf的故事 这篇文章的原文来自:英文原文作者仿照<小王子>中的情节,生动有趣的阐述了小printf从编程小白到专家的成长历程.这是我第一次尝试翻译文章,肯定有很多不足之处,情不要 ...

  2. 准备.Net转前端开发-WPF界面框架那些事,搭建基础框架

    题外话 最近都没怎么写博客,主要是最近在看WPF方面的书<wpf-4-unleashed.pdf>,挑了比较重要的几个章节学习了下WPF基础技术.另外,也把这本书推荐给目前正在从事WPF开 ...

  3. ChartDirector应用笔记(三)

    前言 继上篇文章(Simple bar chart)推出之后,本篇文章继续ChartDirector的使用.在这篇Blog中,博主实现的是soft lighting bar.soft lighting ...

  4. XSS 和 CSRF 攻击

    web安全中有很多种攻击手段,除了SQL注入外,比较常见的还有 XSS 和 CSRF等 一.XSS(Cross Site Scripting)跨站脚本 XSS其实就是Html的注入问题,攻击者的输入没 ...

  5. SQL Server 2008 FILESTREAM特性管理文件

    在SQL Server 2008中,新的FILESTREAM(文件流)特性和varbinary列配合,你可以在服务器的文件系统上存储真实的数据,但可以在数据库上下文内管理和访问,这个特性让SQL Se ...

  6. MVC+EF+esayui初试(一 布局加菜单显示)

    最近都在做linq+ext.net的开发.这两天想学习下MVC和ef,刚好,在看ext.js的时候也喜欢上了esayui,所以就想用mvc+ef+esayui做一个汽车网后台管理来加强下.在这里也把我 ...

  7. SVN 忽略文件但不删除文件

    SVN忽略一些不必要的文件但不删除 如果svn仓库中有一些不希望被别人提交的文件 该如何忽略掉对这个文件的更改但又不删除这个文件呢? 在找了一堆解决方案后得出了如下结论 去除要被忽略文件的版本控制 基 ...

  8. 编程Bug集

    (基础)将“/”用于取余符号,导致非预想结果——1小时后才找到错误原因 9.16

  9. 【JS复习笔记】07 复习感想

    好吧,其实<JavaScript语言精粹>后面还简单介绍了代码风格,优美特性,以及包含的毒瘤.糟粕. 但我很快就看完了,发现其实都在前面讲过了,所以就不写了. 至今为止已经算是把JavaS ...

  10. ActiveReports 9 新功能:创新的报表分层设计理念

    在最新发布的ActiveReports 9报表控件中添加了多项新功能,以帮助你在更短的时间里创建外观绚丽.功能强大的报表系统,本文将重点介绍创新的报表分层设计理念,对报表内容进行分组管理与设计,易于实 ...