implementing compareTo method for several fields

后端 未结 4 1839
自闭症患者
自闭症患者 2021-02-11 10:51

I want to compare two object based on 5-tuple which are: srcAddr, dstAddr, srcPort, dstPort, protocol

here is what i have:

public class Flows implements          


        
4条回答
  •  一个人的身影
    2021-02-11 11:21

    You can write like this also, I have done like this in my project

    public int compareTo(Flows arg0) {
        int comp1, comp2, comp3, comp4;
        comp1 = this.srcAddr.compareTo(arg0.srcAddr);
        comp2 = this.dstAddr.compareTo(arg0.dstAddr);
        comp3 = this.srcPort.compareTo(arg0.srcPort);
        comp4 = this.protocol.compareTo(arg0.protocol);
    
        if (comp1 == 0 && comp2 == 0 && comp3 == 0 && comp4 == 0) {
            return 0;
        } else {
    
            if (comp1 != 0)
                return comp1;
            else {
                if (comp2 != 0)
                    return comp2;
                else {
                    if (comp3 != 0)
                        return comp3;
                    else {
                        if (comp4 != 0)
                            return comp4;
                        else
                            return 0;
                    }
                }
            }
    
        }
    
    }
    

提交回复
热议问题