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. 十分钟搞懂什么是CGI

    原文:CGI Made Really Easy,在翻译的过程中,我增加了一些我在学习过程中找到的更合适的资料,和自己的一些理解.不能算是严格的翻译文章,应该算是我的看这篇文章的过程的随笔吧. CGI真 ...

  2. 高效查看MySQL帮助文档的方法

    在mysql的使用过程中, 可能经常会遇到以下问题: 某个操作语法忘记了, 如何快速查找? 如何快速知道当前版本上某个字段类型的取值范围? 当前版本都支持哪些函数?希望有例子说明.. 当前版本是否支持 ...

  3. jquery获取url参数

    js/jquery 获取url参数 2010年04月27日 星期二 13:45 js代码: function GetQueryString(name) { var reg = new RegExp(& ...

  4. SQL Server里简单参数化的痛苦

    在今天的文章里,我想谈下对于即席SQL语句(ad-hoc SQL statements),SQL Server使用的简单参数化(Simple Parameterization)的一些特性和副作用.首先 ...

  5. .NET中的枚举(Enum)

    摘要:.NET中的枚举分为简单枚举和标志枚举,这次主要总结一下标志枚举适用条件,以及它的使用方法,并在文章的最后列举枚举使用的一些规范. 在刚接触.NET的枚举时,只用简单的枚举,对于标记枚举,只知道 ...

  6. sprint5.0

    团队成员完成自己认领的任务. 燃尽图:理解.设计并画出本次Sprint的燃尽图的理想线.参考图6. 每日立会更新任务板上任务完成情况.燃尽图的实际线,分析项目进度是否在正轨.每天的例会结束后的都为任务 ...

  7. linq之let子句

    在Linq查询中Let子句可以创建一个新的范围变量,并使用该变量保存表达式的结果. 看下面的例子: private void LetQuery() { List<UserBaseInfo> ...

  8. Linq专题之Lambda表达式

    这一节我们讲的Lambda表达式跟匿名函数有关.Lambda表达式就是一个匿名函数,它可以包含表达式和语句,并且可以创建委托和表达式树. Lambda表达式的组成: 输入参数.Lambda运算符(=& ...

  9. csharp:Chart

    http://www.dotnetperls.com/chart using System; using System.Windows.Forms; using System.Windows.Form ...

  10. mysql innodb表 utf8 gbk占用空间相同,毁三观

    昨天因为发生字符集转换相关错误,今天想验证下utf8和gbk中英文下各自空间的差距.这一测试,绝对毁三观,无论中文还是中文+英文,gbk和utf8占用的实际物理大小完全相同,根本不是理论上所述的“UT ...