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. Gradle学习系列之四——增量式构建

    在本系列的上篇文章中,我们讲到了如何读懂Gradle的语法,在本篇文章中,我们将讲到增量式地构建项目. 请通过以下方式下载本系列文章的Github示例代码: git clone https://git ...

  2. PHP 表单验证--安全性--小记

    HTML 表单数据进行适当的验证对于防范黑客和垃圾邮件很重要! -------------------------------------------------------------------- ...

  3. 区间合并 --- Codeforces 558D : Gess Your Way Out ! II

    D. Guess Your Way Out! II Problem's Link: http://codeforces.com/problemset/problem/558/D Mean: 一棵满二叉 ...

  4. Orleans 之 监控工具的使用

    这一节,我们来说说orleans 中的几个实用工具,OrleansHost.OrleansCounterControl.OrleansManager.ClientGenerator. 1.Orlean ...

  5. 重构第20天 提取子类(Extact SubClass)

    理解:提取子类就是把基类中,不是所有子类或者只有少数子类用到的方法,提取出来,调整到子类中去. 详解:下面的代码中我们用到一个单一的类Registration,来处理学生选课信息. public cl ...

  6. c#调用word com组件 替换书签套打

    安装office2007,添加com引用Microsoft Word12.0 Object Library和Microsoft Office12.0 Object Library using Syst ...

  7. 重新想象 Windows 8 Store Apps (34) - 通知: Toast Demo, Tile Demo, Badge Demo

    [源码下载] 重新想象 Windows 8 Store Apps (34) - 通知: Toast Demo, Tile Demo, Badge Demo 作者:webabcd 介绍重新想象 Wind ...

  8. Servlet-Jsp

    Jsp实际就是Servlet. 我们访问Http://localhost:8080/Web/index.jsp的流程: 1 [jsp文件名].jsp转义为[jsp文件名_jsp].java,文件存储在 ...

  9. 你还记的那一年你我学习的-->>用表组织数据*(数据表)

    不知不觉,踏上IT之路,光阴似箭,日月如梭.虽好像回到从前,回到那个无忧无虑的童年,回到那个花样少年的青春;回到那个年少幼稚的小学;回到那个整天幻想的初中;回到那个顽强不屈,誓死不弃的高中;回到那个整 ...

  10. (HY000): Cannot modify @@session.sql_log_bin inside a transaction

    昨天,线上发生一例(HY000): Cannot modify @@session.sql_log_bin inside a transaction代码缺少显示的start transaction控制 ...