關於TreeSet集合進行匿名實現Comparator接口無法序列化
需求
把自定義類按照某個字段排序,並存儲到集合中,然后把類存儲到文件中。
實現
定義stu類,並繼承Serializable接口序列化
class Stu implements Serializable{
private Integer id;
private String name;
private Integer age;
public static final long serialVersionUID = 1L;
public Stu() {
}
public Stu(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
我使用TreeSet集合存儲stu類,按照age排序
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
TreeSet<Stu> treeSet=new TreeSet<>(new Comparator<Stu>() {
結果:在把集合寫入文件中,報了序列化問題
出現了”沒有序列化異常“,找了很久我的Stu也現實了序列化接口,最后問題出現在了我寫的比較器上。
我實現的是匿名內部類Comparator接口,但是java.text.RuleBasedCollator實現了Comparator接口但是卻不支持Serializable接口,就是Comparator沒有實現Serializable接口導致序列化失敗。
解決辦法:
1.不適用匿名內部類Comparator接口在類中繼承Comparable接口,實現compareTo()方法
class Stu implements Serializable,Comparable{
private Integer id;
private String name;
private Integer age;
public static final long serialVersionUID = 1L;
public Stu() {
}
public Stu(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
2.使用AarryList作為中間集合,把TreeSet添加到List集合中,在進行對象流寫入
List<Stu> list=new ArrayList<>(treeSet);