This seems like a pretty standard problem, but it's just so simple I don't know what to do about it. From what I've read elsewhere on SO, this is caused by Generics when ArrayLists are initialized without specifying parameters. I also know that the warning does not come up when I comment out ArrayList<Integer> p = (ArrayList<Integer>)is.readObject();
, so I'm pretty sure there is a generics safety issue with the compiler by me trying to cast the Object
to an ArrayList<Integer>
. How can I save the ArrayList
without causing this?
Here's the code:
import java.util.*;
import java.io.*;
public class FileTest
{
public static void main(String[] args)
{
String fileName = "fred.txt";
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(2);
a.add(3);
a.add(4);
try
{
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(fileName));
os.writeObject(a);
os.close();
}
catch(FileNotFoundException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
try
{
ObjectInputStream is = new ObjectInputStream(new FileInputStream(fileName));
ArrayList<Integer> p = (ArrayList<Integer>)is.readObject();
//for(int i : p) System.out.println(i);
}
catch(FileNotFoundException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
catch(ClassNotFoundException e){e.printStackTrace();}
}
}