0

I had a programming assignment where i had to save separate files, one a log file and the other a dat file. Each one took an arraylist object and saved it in the file but each arraylist was different. I was under a time crunch so i ended up making separate functions for both but i'm wondering if there's a more modular way of doing it. So for example:

 public void saveLog (ArrayList<A> objectArray, File fileName) throws IOException {
    if (!fileName.exists()) {
        logFile.createNewFile();
    }

    FileOutputStream fileoutput = new FileOutputStream(fileName);
    ObjectOutputStream output = new ObjectOutputStream(fileoutput);
    output.writeObject(objectArray);
    output.close();
    fileoutput.close();

}

Is there a way to recode this so it will also take ArrayList"<"B">" ? I tried using ArrayList"<"Object">" but that threw an error. Very new to java so sorry if this seems like a simple question.

2 Answers 2

3

Basically you need to accept an ArrayList which contains objects that can be serialized, this can easily be expressed with a wildcard, eg:

public void saveLog(ArrayList<? extends Serializable> objectArray, File fileName) {
  ..
}

Which means "accept an ArrayList of an unspecified type which implements Serializable interface", which is a requirement for the ObjectOutputStream.

Sign up to request clarification or add additional context in comments.

Comments

0

You could make the method generic on A (and I would prefer the List interface). Also, I would prefer a try-with-resources Statement. Like

public <A> void saveLog(List<A> objectArray, File fileName)
        throws IOException {
    if (!fileName.exists()) {
        logFile.createNewFile();
    }
    try (FileOutputStream fileoutput = new FileOutputStream(fileName);
            ObjectOutputStream output = new ObjectOutputStream(fileoutput)) {
        output.writeObject(objectArray);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.