APPENDIX 1

Additional Features of the JAVA Collections Framework

A1.1 Introduction

The Java Collections Framework has several features beyond those encountered so far in this book. This appendix focuses on two of those features: serialization and fail-fast iterators.

A1.2 Serialization

Suppose we have gone to the trouble of creating a large and complex HashMap object as part of a project. After we have used that HashMap object in an execution of the project, we might want to save the HashMap, on file, so that we can later resume the execution of the project without having to re-construct the HashMap. Fortunately, this is easily done with just a couple of statements.

How? All of the collection classes in the Java Collections Framework implement the Serializable interface that is in the package java.io. This interface has no methods, but merely provides information to the Java virtual machine about sending instances of the class to/from a stream (a sequence of bytes). Specifically, any class that implements the Serializable interface will be able to copy any object in the class to an output stream—that is, to "serialize" the elements in the object. "Deserialization" reconstructs the original object from an input stream.

For a simple example, suppose we have created an ArrayList object named fruits, whose elements are of type string. We can create an Objectoutputstream and then write fruits to the FileOutputstream object whose path is "fruits.ser" as follows:

try { ObjectOutputStream ...

Get Data Structures and the Java Collections Framework, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.