app3 - APPENDIX 3 ADDITIONAL FEATURES OF THE JAVA...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
APPENDIX 3 ADDITIONAL FEATURES OF THE JAVA COLLECTIONS FRAMEWORK A3.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. A3.2 SERIALIZATION Suppose we have gone to the trouble of creating a large and complex ArrayList object as part of a project. After we have used that ArrayList object in an execution of the project, we might want to save the ArrayList , on file, so that we can later resume the execution of the project without having to re-construct the ArrayList . 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. 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 example, suppose we have created an ArrayList object named fruits . We can create an ObjectOutputStream and then write fruits to the FileOutputStream object whose path is “fruits.ser as follows: try 197
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
{ ObjectOutputStream oos = new ObjectOutputStream ( new FileOutputStream ("fruits.ser")); oos.writeObject (fruits); } // try catch (IOException e) { System.out.println (e); } // catch The ArrayList object fruits has been serialized , that is, is saved as a stream of bytes. The file qualifier, “ser”, is an abbreviation of “serializable”, but you are free to use any qualifier you want, or no qualifier. The definition of the writeObject method depends on the class of the object serialized. For example, here is the definition in the ArrayList class: /** * Save the state of the <tt>ArrayList</tt> instance to a stream (that * is, serialize it). * The worstTime(n) is O(n).
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 6

app3 - APPENDIX 3 ADDITIONAL FEATURES OF THE JAVA...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online