Java Reference
In-Depth Information
import java.io.Serializable;
public class Junk implements Serializable {
private static java.util.Random generator = new java.util.Random();
private int answer; // The answer
private double[] numbers; // Valuable data
private String thought; // A unique thought
private static final long serialVersionUID = 9001L;
public Junk(String thought) {
this.thought = thought;
answer = 42;
// Answer always 42
numbers = new double[3+generator.nextInt(4)]; // Array size 3 to
6
for(int i = 0 ; i<numbers.length ; ++i) {
// Populate with
numbers[i] = generator.nextDouble();
// random values
}
}
@Override
public String toString() {
StringBuffer strBuf = new StringBuffer(thought);
strBuf.append('\n').append(String.valueOf(answer));
for(int i = 0 ; i<numbers.length ; ++i) {
strBuf.append("\nnumbers[")
.append(String.valueOf(i))
.append("] = ")
.append(numbers[i]);
}
return strBuf.toString();
}
}
Directory "SerializeObjects"
An object of type Junk has three instance fields: A simple integer that is always 42, a String object, and
an array of double values. The toString() method provides a String representation of a Junk object
that you can output to the command line. The static field generator is not written to the stream when an
object of type Junk is serialized. The only provision you have made for serializing objects of type Junk
is to declare that the class implements the Serializable interface.
You can write objects of this class type to a file with the following program:
Search WWH ::




Custom Search