繁体   English   中英

保存 ArrayList <arraylist<integer> &gt; 归档</arraylist<integer>

[英]Saving an ArrayList<ArrayList<Integer>> to File

我可以毫无问题地将 ArrayList 保存到文件中,但是当我尝试写入和读取ArrayList<ArrayList<Integer>>来归档时,它会将值归零。
我找不到这种格式有效的示例,或者任何关于它为什么不起作用的主题。

有没有人知道为什么会发生这种情况,或者我应该重构为 ArrayList 的 HashMap 来读/写?

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){
                        if (!tempT.contains(list)){ //gets this far and loads null arraylists
                            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);
            }
        }
    }
}

在 LoadPoint 中,your.tempT.contains(list) 失败了,也就是说,它加载了 list [0,1,2,3,4],然后在循环的下一次迭代中,它认为 tempT 已经包含 [ 0,1,2,3.4] 所以不再添加。

如果您取出“包含”测试,它会起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM