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. HT图形组件设计之道(一)

    HT for Web简称HT提供了涵盖通用组件.2D拓扑图形组件以及3D引擎的一站式解决方案,正如Hightopo官网所表达的我们希望提供:Everything you need to create ...

  2. C#类的一些概念

    一.概念 1.类的作用是来模拟现实对象的,一个现实对象可以从两个地方进行描述:特征和行为. 2.类不是你凭空想象的,它只是描述现实对象具体的特征和行为的. 3我们写类只需要写我们所需要的. 4.类是提 ...

  3. redhat Nginx 安装

    1.Nginx 简介 Nginx ("engine x") 是一个高性能的 HTTP 和 反向代理 服务器,也是一个 IMAP/POP3/SMTP 代理服务器. Nginx 是由 ...

  4. ASP.NET十分有用的页面间传值方法

    一.目前在ASP.NET中页面传值共有这么几种方式: 1.表单提交,   <form action= "target.aspx" method = "post&qu ...

  5. 使用win2d实现萤火虫粒子效果

    这几天我在做游戏的标题画面,需要实现随机飞舞的萤火虫.萤火虫会闪烁黄绿色的光,远近不同,并且飞出屏幕边界不久会自动飞回来. 我前一阵子用win2d写了个简单的游戏引擎(现在还是alpha阶段),用它可 ...

  6. C#中dategridview数据导出为excel文件

    先从数据库中获取数据,绑定在datagridview中,再从dategridview中导出为excel文件 1.新建窗体,把控件datagridview和按钮设置好,如图

  7. 重新想象 Windows 8.1 Store Apps (78) - 控件增强: ScrollViewer, FlipView, Popup

    [源码下载] 重新想象 Windows 8.1 Store Apps (78) - 控件增强: ScrollViewer, FlipView, Popup 作者:webabcd 介绍重新想象 Wind ...

  8. javascript: detect mobile devices or browser

    http://detectmobilebrowsers.com/ http://hgoebl.github.io/mobile-detect.js/ http://www.hand-interacti ...

  9. Visual Studio 2013下JSON可视化工具

          Visual Studio 2013现在我们有个小工具可以实现JSON可视化,这样给我们调试JSON提供了便利. JSON这种数据格式已经比较流行,在WEB前端随处可见. 在你需要安装VS ...

  10. xmapp的安装

    搭建网站常识性的你首先得搭建一个服务器. 首先APACHE是世界使用排名第一的WEB服务器软件,但是安装APACHE WEB服务器并不容易.如果你想添加MYSQL.PHP和PERL,那就更难了.所以可 ...