Java 简明教程

Java - Collections Framework

在 Java 2 之前,Java 提供了诸如 Dictionary, Vector, Stack,Properties 等特殊类来存储和操作对象组。尽管这些类非常有用,但它们缺少一个中心统一的主题。因此,您使用 Vector 的方式与您使用 Properties 的方式不同。

Prior to Java 2, Java provided ad hoc classes such as Dictionary, Vector, Stack, and Properties to store and manipulate groups of objects. Although these classes were quite useful, they lacked a central, unifying theme. Thus, the way that you used Vector was different from the way that you used Properties.

Why Collections Framework?

集合框架旨在满足若干目标,例如-

The collections framework was designed to meet several goals, such as −

  1. The framework had to be high-performance. The implementations for the fundamental collections (dynamic arrays, linked lists, trees, and hashtables) were to be highly efficient.

  2. The framework had to allow different types of collections to work in a similar manner and with a high degree of interoperability.

  3. The framework had to extend and/or adapt a collection easily.

为此目的,整个 collections 框架围绕一组标准接口进行设计。提供 LinkedList, HashSet,TreeSet 等这些接口的几个标准实现,您可以按原样使用它们,也可以根据需要实现自己的集合。

Towards this end, the entire collections framework is designed around a set of standard interfaces. Several standard implementations such as LinkedList, HashSet, and TreeSet, of these interfaces are provided that you may use as-is and you may also implement your own collection, if you choose.

Java Collections Framework

集合框架是一个用于表示和操作集合的统一体系结构。所有集合框架包含下列内容:

A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following −

  1. Interfaces − These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy.

  2. Implementations, i.e., Classes − These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures.

  3. Algorithms − These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface.

除了集合之外,该框架还定义了几个映射接口和类。映射存储键值对。虽然在该术语的正确使用中,映射不是集合,但它们与集合完全集成。

In addition to collections, the framework defines several map interfaces and classes. Maps store key/value pairs. Although maps are not collections in the proper use of the term, but they are fully integrated with collections.

Hierarchy of Collection Framework

集合框架的所有类和接口都可以在 java.utli package 中找到。下图显示了 Java 中集合框架的层次结构:

All classes and interfaces for the collection framework are available in java.utli package. The following diagram shows the hierarchy of the collection framework in Java:

hierarchy of collection framework

Java Collection Interfaces

集合框架定义了几个接口。本节概述了每个接口:

The collections framework defines several interfaces. This section provides an overview of each interface −

Sr.No.

Interface & Description

1

The Collection InterfaceThis enables you to work with groups of objects; it is at the top of the collections hierarchy.

2

The List InterfaceThis extends Collection and an instance of List stores an ordered collection of elements.

3

The SetThis extends Collection to handle sets, which must contain unique elements.

4

The SortedSetThis extends Set to handle sorted sets.

5

The MapThis maps unique keys to values.

6

The Map.EntryThis describes an element (a key/value pair) in a map. This is an inner class of Map.

7

The SortedMapThis extends Map so that the keys are maintained in an ascending order.

8

The EnumerationThis is legacy interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects. This legacy interface has been superceded by Iterator.

Java Collection Classes

Java 提供了一组实现 Collection 接口的标准集合类。有些类提供了可按原样使用的完整实现,而另一些类是抽象类,提供用作创建具体集合的起点的骨架实现。

Java provides a set of standard collection classes that implement Collection interfaces. Some of the classes provide full implementations that can be used as-is and others are abstract class, providing skeletal implementations that are used as starting points for creating concrete collections.

标准集合类总结在以下表中 −

The standard collection classes are summarized in the following table −

Sr.No.

Class & Description

1

AbstractCollection Implements most of the Collection interface.

2

AbstractList Extends AbstractCollection and implements most of the List interface.

3

AbstractSequentialList Extends AbstractList for use by a collection that uses sequential rather than random access of its elements.

4

LinkedListImplements a linked list by extending AbstractSequentialList.

5

ArrayListImplements a dynamic array by extending AbstractList.

6

AbstractSet Extends AbstractCollection and implements most of the Set interface.

7

HashSetExtends AbstractSet for use with a hash table.

8

LinkedHashSetExtends HashSet to allow insertion-order iterations.

9

TreeSetImplements a set stored in a tree. Extends AbstractSet.

10

AbstractMap Implements most of the Map interface.

11

HashMapExtends AbstractMap to use a hash table.

12

TreeMapExtends AbstractMap to use a tree.

13

WeakHashMapExtends AbstractMap to use a hash table with weak keys.

14

LinkedHashMapExtends HashMap to allow insertion-order iterations.

15

IdentityHashMapExtends AbstractMap and uses reference equality when comparing documents.

AbstractCollection、AbstractSet、AbstractList、AbstractSequentialList 和 AbstractMap 类提供了核心集合接口的基本实现,以最大程度减少实现这些接口所需的工作量。

The AbstractCollection, AbstractSet, AbstractList, AbstractSequentialList and AbstractMap classes provide skeletal implementations of the core collection interfaces, to minimize the effort required to implement them.

java.util 定义的以下旧类已在上一章中讨论过−

The following legacy classes defined by java.util have been discussed in the previous chapter −

Sr.No.

Class & Description

1

VectorThis implements a dynamic array. It is similar to ArrayList, but with some differences.

2

StackStack is a subclass of Vector that implements a standard last-in, first-out stack.

3

DictionaryDictionary is an abstract class that represents a key/value storage repository and operates much like Map.

4

HashtableHashtable was part of the original java.util and is a concrete implementation of a Dictionary.

5

PropertiesProperties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and the value is also a String.

6

PriorityQueuePriorityQueue class is an unbounded priority queue based on a priority heap. A priority queue relying on natural ordering also does not permit insertion of non-comparable objects.

7

BitSetA BitSet class creates a special type of array that holds bit values. This array can increase in size as needed.

8

ArrayDequeArrayDeque class provides resizable-array and implements the Deque interface. Array deques have no capacity restrictions so they grow as necessary to support usage.

9

EnumMapEnumMap class is a specialized Map implementation for use with enum keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created.

10

QueueThe queue interface is provided in java.util package and it implements the Collection interface. The queue implements FIFO i.e. First In First Out. This means that the elements entered first are the ones that are deleted first.

11

DequeEnumMap class is a specialized Map implementation for use with enum keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created.

The Collection Algorithms

集合框架定义了可以应用于集合和映射的几种算法。这些算法在 Collections 类中被定义为静态方法。

The collections framework defines several algorithms that can be applied to collections and maps. These algorithms are defined as static methods within the Collections class.

其中有些方法会抛出 ClassCastException,当尝试比较不兼容的类型时会发生 ClassCastException 错误,当尝试修改不可修改集合时会发生 UnsupportedOperationException 错误。

Several of the methods can throw a ClassCastException, which occurs when an attempt is made to compare incompatible types, or an UnsupportedOperationException, which occurs when an attempt is made to modify an unmodifiable collection.

集合定义了三个静态变量:EMPTY_SET、EMPTY_LIST 和 EMPTY_MAP。所有都是不可变的。

Collections define three static variables: EMPTY_SET, EMPTY_LIST, and EMPTY_MAP. All are immutable.

Sr.No.

Algorithm & Description

1

The Collection AlgorithmsHere is a list of all the algorithm implementation.

How to Use an Iterator?

通常,您会希望在集合中的元素间循环。例如,您可能希望显示每个元素。

Often, you will want to cycle through the elements in a collection. For example, you might want to display each element.

最简单的做法是使用迭代器,它是一个实现了 Iterator 或 ListIterator 接口的对象。

The easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface.

迭代器使您能够在集合中循环,获取或删除元素。ListIterator 扩展了 Iterator,以允许双向遍历列表并修改元素。

Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator extends Iterator to allow bidirectional traversal of a list and the modification of elements.

Sr.No.

Iterator Method & Description

1

Using Java IteratorHere is a list of all the methods with examples provided by Iterator and ListIterator interfaces.

How to Use a Comparator?

TreeSet 和 TreeMap 都将元素存储在排序顺序中。但是,正是比较器精确地定义了排序顺序的含义。

Both TreeSet and TreeMap store elements in a sorted order. However, it is the comparator that defines precisely what sorted order means.

该接口允许我们对给定集合进行任意次数的不同方式的排序。此接口还可以用于对任何类的任何实例(包括我们无法修改的类)进行排序。

This interface lets us sort a given collection any number of different ways. Also this interface can be used to sort any instances of any class (even classes we cannot modify).

Sr.No.

Iterator Method & Description

1

Using Java ComparatorHere is a list of all the methods with examples provided by Comparator Interface.

How to Use a Comparable?

TreeSet 和 TreeMap 都按顺序存储元素。我们可以使用 Comparable 接口精确定义排序顺序的意思。

Both TreeSet and TreeMap store elements in a sorted order. We can use Comparable interface that defines precisely what sorted order means.

该接口允许我们对给定集合进行任意次数的不同方式的排序。此接口还可以用于对任何类的任何实例(包括我们无法修改的类)进行排序。

This interface lets us sort a given collection any number of different ways. Also this interface can be used to sort any instances of any class (even classes we cannot modify).

Sr.No.

Iterator Method & Description

1

Using Java ComparableHere is a list of all the methods with examples provided by Comparable Interface.

Summary

Java 集合框架为程序员提供了预先打包的数据结构和用于操作这些数据结构的算法。

The Java collections framework gives the programmer access to prepackaged data structures as well as to algorithms for manipulating them.

集合是可以引用其他对象的类。集合接口声明了可在每种类型的集合上执行的操作。

A collection is an object that can hold references to other objects. The collection interfaces declare the operations that can be performed on each type of collection.

集合框架的类和接口都包含在包 java.util 中。

The classes and interfaces of the collections framework are in package java.util.