您的位置:首页 > 编程语言 > Java开发

Thinking in java-9 参数化类型和容器

2017-06-16 10:06 218 查看

1.容器–container

为何有container这种东西?

三个问题:

不明确解决问题需要的对象的数量;

不明确对象存在时间;

不知道如何存储这些对象时。

解决方案:创建另外一种对象;这种新型对象保存其他对象的引用。

选取容器的两个原则:

不同容器提供了不同的外部接口和外在行为。比如说栈stack所能提供的功能和队列queue区别很大,和集合set与列表list不同。

其二,不同容器对于某些相同的操作有不同的效率。比如ArrayList和LinkedList,它们提供了相同的接口,但是却有不同的效率。

如:ArrayList对于随机的访问元素而言都是常量时间的;而对于LinkedList而言,将话费更多时间定位待访问对象。

对于LinkdedList而言,插入和删除数据(尤其在List中间位置)代价更小。

Used when? You don’t know how many objects you’re going to need to solve a particular problem, or how long they will last. You also don’t know how to store those objects.

The solution to most problems in object-oriented design seems flippant: You create another type of object. The new type of object solves this particular problems holds references to other objects.

There are tow reasons that you need a choice of containers.

First, containers provide different types of interfaces and external behavior. A stack has different interface and behavior than a queue,which is different from a set or a list. One of these may provide a flexible solution to your problem than the other.

Second, different containers have different efficiencies for certain operations. For example, ArrayList and LinkedList, identical interfaces and external behaviors:

ArrayList: randomly accessing elements constant-time operation regardless of the element you select, while in a LinkedList longer to find elements farther down on the list.

LinkedList: insert an element in the middle of a sequence it’s cheaper in LinkedList.

2.参数化类型–parameterized types

Before SE5, containers hold the one universal type in Java: Object. The singly rooted hierarchy means that anything is an Object, so a container that holds Objects can hold anything, which makes containers easy to reuse.

You simply add object references to it and later ask for them back.

Add: upcast to Object, thus losing its character.

Fetch: downcast, cast down to a more specific type. It’s not completely dangerous, because if you downcast to the wrong thing you’ll get a runtime error called an exception.

Downcasting and the runtime check requires extra time for the running program and extra effort form the program. Create a container so that it knows the types that it holds, eliminating the need for the downcast and a possible mistake.

Java参数化类型–所谓的泛型,最初是为了解决容器的存取问题,为了使容器更易用。

在Java SE5之前,容器只保存一种统一的类型–Object。java单继承机制意味着所有的对象都可以归结到Object上来,所以一个能存放Object的容器能存放所有对象,这个特点使得容器很重用起来很容易。

我们只需简单地将一个对象的引用放入容器,然后将它们取回来。

Add: 放对象时,对象将被upcast成Object类型,因而丧失了其本来特征。

那为何还要有参数化类型–泛型呢?

因为downcast和运行时检验都是在运行时所做的工作,这需要消耗额外的时间和代价。创建参数化容器后,可以把这些工作在编译时检验,减少了downcast和产生bug的可能。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息