java中的treeSet序列化

时间:2016-01-08 18:30:46

标签: java serialization

我有一个类,它扩展了一个实现serializable本身的超类。我的类包含treeSet字段和连接的比较器。我想使类可序列化,因为我将在集群上运行它。 访问java.io.NotSerializableException字段时出现treeSet错误。 有谁知道我应该如何解决它?

public static class bounderyRecordsFilter implements FilterFunction  {
    public ArrayList<String> sortingkeyStart;
    public ArrayList<String> sortingkeyEnd;
    public  TreeSet<boundery> intervals ;
    public int pass;

       public   Comparator<boundery> Interval_order =   new Comparator<boundery>() {
            public int compare(boundery e1, boundery e2) {
                int comp_res=0;
                     comp_res= e1.getStartInterval() .compareToIgnoreCase(e2.getStartInterval());
                return comp_res;
            }
        };  

    public bounderyRecordsFilter(ArrayList<String> sortingkeyStart,ArrayList<String> sortingkeyEnd, int pass){
        super();
        intervals = new TreeSet<boundery>(Interval_order);
        for (int i=0 ; i< 4 ; i++)
        {
            boundery tempInterval = new boundery();
            ...             
            intervals.add(tempInterval) ;
        }
         this.sorkingkeyStart = sorkingkeyStart ; 
         this.sorkingkeyEnd = sorkingkeyEnd ;
         this.pass = pass;
    }

    @Override
    public boolean filter(Tuple2<Integer, String> inputTuple)
            throws Exception {
        boundery tempInterval = new boundery();
        boundery outputInterval = new boundery();

        tempInterval .setStartInterval(inputTuple.f19);
        outputInterval  = intervals.lower(tempInterval);

        if (outputInterval. getEndInterval().compareToIgnoreCase(inputTuple.f2) >0)
            return true;
        else
            return false;


    }

}

2 个答案:

答案 0 :(得分:6)

您必须同时使用bounderyComparator Serializable。您没有提供有关boundery的详细信息,但是使Comparator可序列化的一种流行方式是将其编写为:

enum IntervalOrder implements Comparator<boundery> {
   INSTANCE;
   public int compare(boundery e1, boundery e2) {
     return e1.getStartInterval() .compareToIgnoreCase(e2.getStartInterval());
   }
}; 

然后写new TreeSet<boundery>(IntervalOrder.INSTANCE)。枚举可以自动序列化和单例化。

答案 1 :(得分:1)

Comparator类也必须实现Serializable。 像这样:

public class StringComperator implements Comparator<String>, Serializable
{
    @Override
    public int compare(String n1, String n2)
    {
        return n1.compareTo(n2);
    }
}