Treeset序列化到文件失败

记录一下treeset序列化到文件失败的问题

源代码

 @Test
    public void treeset序列化测试() throws IOException {
        Set<Tuple2<String, Double>> set = new TreeSet<>(Comparator.comparing(o->o.f0));
        set.add(Tuple2.of("1", 2.0));
        set.add(Tuple2.of("2", 2.0));
        set.add(Tuple2.of("3", 2.0));
        Set<Tuple2<String, Double>> set2 = new HashSet<>(set);

        String fileName = "list.txt";
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName));
        oos.writeObject(set);
        System.out.println("List对象已成功存储到文件中!");
    }

 运行的时候,序列化set2不会报错

运行的时候,序列化set会报错

根据这个提示问了下gpt,他说是我的序列化器有问题,说让我把序列化器也实现一下Serializable接口

 我照做了,代码改成了如下所示

 @Test
    public void treeset序列化测试() throws IOException {
        Set<Tuple2<String, Double>> set = new TreeSet<>(new MyComparator());
        set.add(Tuple2.of("1", 2.0));
        set.add(Tuple2.of("2", 2.0));
        set.add(Tuple2.of("3", 2.0));
        Set<Tuple2<String, Double>> set2 = new HashSet<>(set);

        String fileName = "list.txt";
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName));
        oos.writeObject(set);
        System.out.println("List对象已成功存储到文件中!");
    }
    public class MyComparator implements Comparator<Tuple2<String, Double>>, Serializable {
        @Override
        public int compare(Tuple2<String, Double> o1, Tuple2<String, Double> o2) {
            // 比较逻辑
            return o1.f0.compareTo(o2.f0);
        }
    }

运行一下还是报错,说我的主类没有序列化

于是把主类上面也加上了序列化

public class SalesGrowthRateTest implements Serializable {
 @Test
    public void treeset序列化测试() throws IOException {
        Set<Tuple2<String, Double>> set = new TreeSet<>(new MyComparator());
        set.add(Tuple2.of("1", 2.0));
        set.add(Tuple2.of("2", 2.0));
        set.add(Tuple2.of("3", 2.0));
        Set<Tuple2<String, Double>> set2 = new HashSet<>(set);

        String fileName = "list.txt";
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName));
        oos.writeObject(set);
        System.out.println("List对象已成功存储到文件中!");
    }
    public class MyComparator implements Comparator<Tuple2<String, Double>>, Serializable {
        @Override
        public int compare(Tuple2<String, Double> o1, Tuple2<String, Double> o2) {
            // 比较逻辑
            return o1.f0.compareTo(o2.f0);
        }
    }
}

 运行一下是成功的!!!

但是我并不知道为什么,需要主类也进行序列化,我的比较器不是已经序列化过了吗?求赐教

哦,对了还有一种写法,主类不需要序列化,把比较器类改成静态的也可以运行成功。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值