Collections.sort()不使用compareTo覆盖进行排序

时间:2019-03-04 22:12:40

标签: java

标题说明-这是我的Packet类-我正尝试按packetNum的升序进行排序:

public class Packet implements Comparable<Packet>{
    private short packetNum;
    private short authKey;
    private byte[] audio;

    public Packet()
    {
        packetNum = 0;
        authKey = 0;
        audio = null;
    }

    public Packet(short packetNum, short authKey, byte[] audio)
    {
        this.packetNum = packetNum;
        this.authKey = authKey;
        this.audio = audio;
    }

    @Override
    public int compareTo(Packet other) {
        int cmp = 0;
        if (this.packetNum < other.packetNum) {
            cmp = -1;
        }
        if (this.packetNum == other.packetNum) {
            cmp = 0;
        }
        else {
            cmp = 1;
        }
        return cmp;
    }
}

这是我在另一个类的main中的排序代码(在while循环内):

//Packet constructed
Packet received = new Packet(packetNumReceived, authKeyReceived, encryptedAudio);

//Get packet num
short packetNum = received.getPacketNum();

//Hold block for reordering (16 packets)
ArrayList<Packet> block = new ArrayList<Packet>();

while (running) {
    //Add packet to ArrayList
    block.add(received);
    System.out.println(packetNum);
    //Re-order packets
    if (block.size() == 16) {
        Collections.sort(block);
        for (int i = 0; i < block.size(); i++) {
            //print out the sorted packet numbers
            System.out.println(block.get(i).getPacketNum());
            player.playBlock(block.get(i).getAudio());
        }
        block.clear();
    }
}

在排序之前和之后,打印的数据包编号以相同(不正确)的顺序排列。我还直接检查了数组元素,并且顺序根本没有改变。这些代码部分是唯一一次完全触摸/引用Packet类的时间,不确定我在做什么错。这是我仅有的2个类,并且它们之间没有重用的变量名。

3 个答案:

答案 0 :(得分:3)

@Override
public int compareTo(Packet other) {
    int cmp = 0;
    if (this.packetNum < other.packetNum) {
        cmp = -1;
    }
    if (this.packetNum == other.packetNum) {
        cmp = 0;
    }
    else {
        cmp = 1;
    }
    return cmp;
}

在此代码中,即使this.packetNum == other.packetNum给出的错误信息也要返回 1 ,即使您想返回 -1

您忘记了另一个:

    (...) 
    else if (this.packetNum == other.packetNum) {
        cmp = 0;
    }
    (...)

答案 1 :(得分:3)

由于丢失了1packetNum不匹配时,您总是返回else if

@Override
public int compareTo(Packet other) {
    int cmp = 0; // default to zero
    if (this.packetNum < other.packetNum) {
        cmp = -1;  // set to -1 in one case
    } // MISSING ELSE!
    if (this.packetNum == other.packetNum) {
        cmp = 0;  // set to zero if equal
    }
    else {
        cmp = 1;  // set to 1 if NOT EQUAL!
    }
    return cmp;
}

正如其他人指出的那样,将它们相减或使用Short.compare也可以使此代码更简洁和可读。

答案 2 :(得分:1)

不要编码已经为您编码的内容,请使用

Short.compare(this.packetNum, other.packetNum);

Javadoc