File

Growable array of ints example

In this example we shall show you how to create a growable array of ints. We have created an example of how to create serializable objects and how to store them in Files and then retrive them and create copies of the objects. We have performed the following steps:

  • SerialIntList implements the Serializable. It has two protected properties, an int array and a transient int property.It has four methods: The get(int ind) method returns the value of the array in a specified position. The resize(int size) method creates a new array resizing the old one.The add(int i) method adds a value to the array.The writeObject(ObjectOutputStream out) method writes the array to an ObjectOutputStream. The equals(Object o) and hashcode() methods of Object are overriden here.
  • DataStructure class also implements the Serializable. It has a String property, an int array property and a Datastructure property. It overrides the toString() method of Object.
  • We have created a method, store(Serializable o, File f) that creates a new ObjectOutputStream to write a Serializable object. The method load(File f) loads a file using an ObjectInputStream.
  • The method Object deepclone(final Serializable o) creates a PipedOutputStream and a PipedInputStream. Then it creates a new Thread that uses the piped streams in its run() method to write to an ObjectOutputStream and then reads from an ObjectInputStream.
  • We create a new DataStructure instance and set values to its properties.
  • We create a new File and use store(Serializable o, File f) method to write the datastructure to the file.
  • Then we use the load(File f) method to load the file. We use the deepclone(Serializable o) to create the clone of the object,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.Serializable;


class SerialIntList implements Serializable {
    
    protected int[] intArray = new int[8];
    protected transient int length = 0;

    public int get(int ind) {

  

  if (ind >= length) {


throw new ArrayIndexOutOfBoundsException(ind);

  } else {


return intArray[ind];

  }
    }

    public void add(int i) {

  if (intArray.length == length) {


resize(intArray.length * 2); 

  }

  intArray[length++] = i; 
    }

    protected void resize(int size) {

  int[] newdata = new int[size]; 

  System.arraycopy(intArray, 0, newdata, 0, length); // Copy array elements.

  intArray = newdata; // Replace old array
    }

    private void writeObject(ObjectOutputStream out) throws IOException {

  if (intArray.length > length) {


resize(length); // Compact the array.

  }

  out.defaultWriteObject(); // Then write it out normally.
    }

    @Override
    public boolean equals(Object o) {

  if (!(o instanceof SerialIntList)) {


return false;

  }

  SerialIntList that = (SerialIntList) o;

  if (this.length != that.length) {


return false;

  }

  for (int i = 0; i < this.length; i++) {


if (this.intArray[i] != that.intArray[i]) {


    return false;


}

  }

  return true;
    }

    @Override
    public int hashCode() {

  int code = 1; 

  for (int i = 0; i < length; i++) {


code = code * 997 + intArray[i];

  }

  return code;
    }
}

public class Main {

    static void store(Serializable o, File f) throws IOException {

  ObjectOutputStream ostream = new ObjectOutputStream(new FileOutputStream(f));

  ostream.writeObject(o); 

  ostream.close();
    }

    static Object load(File f) throws IOException, ClassNotFoundException {

  ObjectInputStream instream =  new ObjectInputStream(new FileInputStream(f));

  return instream.readObject(); 
    }

    static Object deepclone(final Serializable o) throws IOException, ClassNotFoundException {


  final PipedOutputStream pipeout = new PipedOutputStream();

  

  PipedInputStream pipein = new PipedInputStream(pipeout);


  Thread writer = new Thread() {



@Override


public void run() {


    ObjectOutputStream out = null;


    try {



  out = new ObjectOutputStream(pipeout);



  out.writeObject(o);


    } catch (IOException e) {


    } finally {



  try {




out.close();



  } catch (Exception e) {



  }


    }


}

  };

  // Start serializing and writing

  writer.start();


  ObjectInputStream in = new ObjectInputStream(pipein);

  return in.readObject();
    }

    static class DataStructure implements Serializable {


  String message;

  int[] data;

  DataStructure other;


  @Override

  public String toString() {


String s = message;


for (int i = 0; i < data.length; i++) {


    s += " " + data[i];


}


if (other != null) {


    s += "nt" + other.toString();


}


return s;

  }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {



  DataStructure structure = new DataStructure();

  

  structure.message = "Java Code Geeks rocks!";

  

  structure.data = new int[]{1, 2, 3, 4, 5};

  

  structure.other = new DataStructure();

  

  structure.other.message = "JavaCodeGeeks is the best!";

  

  structure.other.data = new int[]{9, 8, 7};


  System.out.println("Data: " + structure);


  File f = new File("C:/Users/nikos7/Desktop/output2.txt");

  

  System.out.println("Save to file");

  Main.store(structure, f);


  structure = (DataStructure) Main.load(f);

  System.out.println("Read : " + structure);


  

  DataStructure ds2 = (DataStructure) Main.deepclone(structure);

  structure.other.message = null;

  structure.other.data = null; 

  System.out.println("Deepcloning: " + ds2);
    }
}

Output:

Data: Java Code Geeks rocks! 1 2 3 4 5
	JavaCodeGeeks is the best! 9 8 7
Save to file
Read : Java Code Geeks rocks! 1 2 3 4 5
	JavaCodeGeeks is the best! 9 8 7
Deepcloning: Java Code Geeks rocks! 1 2 3 4 5
	JavaCodeGeeks is the best! 9 8 7

 
This was an example of how to create a growable array of ints in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button