Drivebyluna
Drivebyluna

Reputation: 364

Create a function that takes an Arraylist of any type?

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.

Upvotes: 0

Views: 60

Answers (2)

Jack
Jack

Reputation: 133577

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.

Upvotes: 3

Elliott Frisch
Elliott Frisch

Reputation: 201447

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);
    }
}

Upvotes: 0

Related Questions