记录一下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);
}
}
}
运行一下是成功的!!!
但是我并不知道为什么,需要主类也进行序列化,我的比较器不是已经序列化过了吗?求赐教
哦,对了还有一种写法,主类不需要序列化,把比较器类改成静态的也可以运行成功。