Skip to content
Advertisement

Saving an ArrayList<ArrayList> to File

I am able to save an ArrayList to a file without any problems, but when I try to write and read an ArrayList<ArrayList<Integer>> to file it nulls out the values.
I cannot find an example of this format working, or any subject matter as to why it wouldn’t work.

Does anyone have any insight into why this might happen, or should I just refactor into a HashMap of ArrayList to read/write?

public class SaveTest{

public static void SavePoint(ArrayList<ArrayList<Integer>> numbers) throws IOException {
        FolderCreator.createFolder();
        ObjectOutputStream ousT = new ObjectOutputStream(new FileOutputStream(filePathT));
        try{
            for (Object x : numbers) {
                if(x!=null) {
                    ousT.writeObject(x); //----not writing data correctly
                }
            }
            ousT.flush();
            ousT.close();
        }catch(Exception e){e.printStackTrace();}
    }

public static ArrayList<ArrayList<Integer>> LoadPoint() throws IOException{
        ArrayList<ArrayList<Integer>> tempT = new ArrayList<>();
        try (ObjectInputStream oisT = new ObjectInputStream(new FileInputStream(filePathT))){
            try {
                while (true){
                    ArrayList<Integer> list = (ArrayList<Integer>)oisT.readObject();
                    if (list != null){
                            tempT.add(list);
                    }else{System.out.println("Null at load");}//----------------------------
                }
            }catch(EOFException e){}
            catch (ClassNotFoundException c){System.out.println("Class not found");}
            oisT.close();
            return tempT;
        }
    }
 
    public static void main(String[] args){
        ArrayList<ArrayList<Integer>> lists = new ArrayList<>();
        ArrayList<Integer> nums1 = new ArrayList<>();
        ArrayList<Integer> nums2 = new ArrayList<>();
        ArrayList<Integer> nums3 = new ArrayList<>();

        for(int i=0; i<5; i++){
            nums1.add(i);
            nums2.add(i);
            nums3.add(i);
        }
        lists.add(nums1);
        lists.add(nums2);
        lists.add(nums3);

        SavePoint(lists);
        ArrayList<ArrayList<Integer>> listsReturn = LoadPoint();
        for(ArrayList<Integer> list : listReturn){
            for(int n : list){
                System.out.print("Next number: " + n);
            }
        }
    }
}

Advertisement

Answer

In LoadPoint, your !tempT.contains(list) is failing. In other words, it loads list [0,1,2,3,4], and then in the next iteration of the loop, it thinks that tempT already contains [0,1,2,3,4] so doesn’t add it again.

If you take out the “contains” test, it works.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement