How do I create a method that returns an ArrayList of a given parameter in the constructor?

I created .dat files to store an arraylist of objects using implements Serializable

in my object class. I have two classes Member and Style and I want to store them in arrayList in a .dat file and I got it all to work.

I created a ReadData class that takes a fileLocation parameter as a parameter. and then 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 in an arraylist and the save method just stores the arraylist. For example: (Only with some attempts to 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 every time, I'm thinking about creating 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 the Member object comes from a parameter and ArrayList<Style>

when it's Style.

Anyone who can help me? or help me achieve this in another way?

+3


source to share


1 answer


You're so close to that right. Below is the relevant code to make it common. Unfortunately, java serialized objects are not familiar with the type, so you will need to cast the object some more.

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

      

If you want to learn more about general programming, the 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 a generic class.



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

    }
}

      

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

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

      

+3


source







All Articles