Java Reference
In-Depth Information
4.9
ArrayLists and Serialisation
It is much more effi cient to save a single
ArrayList
to disc than it is to save a series
of individual objects. Placing a series of objects into a single
ArrayList
is a very neat
way of packaging and transferring our objects. This technique carries another sig-
nifi cant advantage: we shall have some form of
random access
, via the
ArrayList
class's
get
method (albeit based on knowing each element's position within the
ArrayList
). Without this, we have the considerable disadvantage of being restricted
to serial access only.
Example
This example creates three objects of class
Personnel
(as featured in the example at
the end of Sect.
4.6
) and uses the
add
method of class
ArrayList
to place the
objects into an
ArrayList
. It then employs a 'for-each' loop and the 'get' meth-
ods of class
Personnel
to retrieve the data properties of the three objects.
We could use the same
ArrayList
object for sending objects out to the fi le and
for receiving them back from the fi le, but two
ArrayList
objects have been used
below simply to demonstrate beyond any doubt that the values have been read back
in (and are not simply the original values, still held in the
ArrayList
object).
import java.io.*;
import java.util.*;
public class ArrayListSerialise
{
public static void main(String[] args)
throws IOException, ClassNotFoundException
{
ObjectOutputStream outStream =
new ObjectOutputStream(
new FileOutputStream("personnelList.dat"));
ArrayList<Personnel> staffListOut =
new ArrayList<>();
ArrayList<Personnel> staffListIn =
new ArrayList<>();
Personnel[] staff =
{new Personnel(123456,"Smith", "John"),
new Personnel(234567,"Jones", "Sally Ann"),
new Personnel(999999,"Black", "James Paul")};
for (int i=0; i<staff.length; i++)
staffListOut.add(staff[i]);
outStream.writeObject(staffListOut);
outStream.close();
ObjectInputStream inStream =
Search WWH ::
Custom Search