I feel like I'm making a dumb mistake because I've been able to do this successfully before, I'm trying to read a file to an Object ArrayList, here's the method.
public static void readFile (String fileName, ArrayList <Pokemon> newPokedex) {
try{
FileInputStream readData = new FileInputStream(fileName);
ObjectInputStream readStream = new ObjectInputStream(readData);
newPokedex = (ArrayList<Pokemon>) readStream.readObject();
readStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
It'll work if I don't add parameters, but every time I do, it tells me my ArrayList is empty.
public static void main (String [] args) {
Pokemon.readFile("Pokedex.txt", Pokemon.Pokedex);
System.out.println(Pokedex.size());
}
My write method works just fine and it'll also print the correct size when I tell it to print it in the method
CodePudding user response:
Your error lies in the way you are using the
ArrayList <Pokemon> newPokedex
parameter.
In this line:
newPokedex = (ArrayList<Pokemon>) readStream.readObject();
you are not reading into the list that you provided as a parameter, instead you are overriding the list reference where the parameter is pointing. But that does not change the list reference outside your method. This is a common mistake.
If you use this line of code instead of the original, it should work:
newPokedex.addAll((ArrayList<Pokemon>) readStream.readObject());
Now you are actually adding all the items from the list that you read from the file into the list that you have provided as a parameter.