Jeggy
Jeggy

Reputation: 1650

How to create method that returns ArrayList of given parameter in constructor?

I've created .dat files to save a arraylist of objects using the implements Serializable on my object class. I have these two classes Member and Style, and I want to save them into an arrayList into .dat file, and I have gotten all this to work..

I have created a ReadData class which takes a fileLocation as parameter. and then has these methods

public boolean load() { 
public boolean save() { 
public ArrayList<Member> getMembers(){ 
public boolean add(Object [] member) {

The load method just takes everything from the .dat file and puts it into the arraylist and save method just saves the arraylist. Like this: ( Just with some try catch also ;) )

/* load Method */
FileInputStream fileIn = new FileInputStream(fileLocation); 
ObjectInputStream in = new ObjectInputStream(fileIn);
this.objects = (ArrayList<Member>) in.readObject(); // <-- That Member needs to be generic also..

/* save Method */
File yourFile = new File(fileLocation); 
yourFile.createNewFile(); 
fileOut = new FileOutputStream(fileLocation, false); 
out = new ObjectOutputStream(fileOut); 
out.writeObject(objects);

And instead of creating a new class each time, I'm thinking about making a generic class that works with everything. So I could use it something like this:

ReadData membersFile = new ReadData("members.dat", new Member());
ReadData stylesFile = new ReadData("styles.dat", new Style());

So somehow my arraylist in the ReadData class will be ArrayList<Member> when Member object is coming from the parameter and the ArrayList<Style> when it's Style.

Someone that can help me to do this? or help me to achieve this in some other way?

Upvotes: 3

Views: 928

Answers (1)

yxre
yxre

Reputation: 3704

You are so close to getting this right. Below is the relevant code to make this generic. Unfortunately, java serialized objects are not type aware, so you will need to cast the object still.

public <T> ArrayList<T> ReadData(String filename, T type) {
    .....
    this.objects = (ArrayList<T>) in.readObject();
    .....
}

If you want to know more about generic programming, oracle has written a solid tutorial that will show you the basics.

In addition to changing the method signatures for your class, you will need to make the class generic.

public class ReadDataMembers<T> {
    public ReadDataMember(String filename) {

    }
}

You don't need to pass in the type through the constructor, but you can use the following syntax

ReadDataMembers rdm = new ReadDataMembers<Member>("member.dat");

Upvotes: 2

Related Questions