Methods Summary |
---|
public void | add(int x)Add an int to the array, growing the array if necessary
if (data.length==size) resize(data.length*2); // Grow array if needed.
data[size++] = x; // Store the int in it.
|
public boolean | equals(java.lang.Object o)Does this object contain the same values as the object o?
We override this Object method so we can test the class.
if (!(o instanceof SerialIntList)) return false;
SerialIntList that = (SerialIntList) o;
if (this.size != that.size) return false;
for(int i = 0; i < this.size; i++)
if (this.data[i] != that.data[i]) return false;
return true;
|
public int | get(int index)Return an element of the array // Index of next unused element of array
if (index >= size) throw new ArrayIndexOutOfBoundsException(index);
else return data[index];
|
public int | hashCode()We must override this method when we override equals().
int code = 1; // non-zero to hash [0] and [] to distinct values
for(int i = 0; i < size; i++)
code = code*997 + data[i]; // ignore overflow
return code;
|
public static void | main(java.lang.String[] args)A main() method to prove that it works
SerialIntList list = new SerialIntList();
for(int i = 0; i < 100; i++) list.add((int)(Math.random()*40000));
SerialIntList copy = (SerialIntList)Serializer.deepclone(list);
if (list.equals(copy)) System.out.println("equal copies");
Serializer.store(list, new File("intlist.ser"));
|
private void | readObject(java.io.ObjectInputStream in)Restore the transient size field after deserializing the array.
The serialization mechanism automatically calls this method.
in.defaultReadObject(); // Read the array normally.
size = data.length; // Restore the transient field.
|
protected void | resize(int newsize)An internal method to change the allocated size of the array
int[] newdata = new int[newsize]; // Create a new array
System.arraycopy(data, 0, newdata, 0, size); // Copy array elements.
data = newdata; // Replace old array
|
private void | writeObject(java.io.ObjectOutputStream out)Get rid of unused array elements before serializing the array. This
may reduce the number of array elements to serialize. It also makes
data.length == size, so there is no need to safe the (transient) size
field. The serialization mechanism will automatically call this method
when serializing an object of this class. Note that this must be
declared private.
if (data.length > size) resize(size); // Compact the array.
out.defaultWriteObject(); // Then write it out normally.
|