Collections.sort() not sorting with compareTo Override

java collections sort comparator
java comparator
java sort list of objects by date property
java sort arraylist of objects by field
collections.sort not working
sort list of objects in java without comparator
java collections sort ascending or descending
java comparable

As the title states - here's my Packet class - I'm trying to sort into ascending order of 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;
    }
}

And here's my sorting code in another class' main (inside a while loop):

//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();
    }
}

The packet numbers printed are in the same (incorrect) order, before and after the sort. I've also check the array elements directly, and the order is not changed at all. These sections of code are the only time the Packet class is touched/referenced at all, not sure what I'm doing wrong. These are my only 2 classes, and there are no reused variable names across them.


@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;
}

In this code, you are returning 1 if this.packetNum == other.packetNum gives you false, even if you wanted to return -1.

You forgot an else:

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

Sorting with Comparable and Comparator in Java, forEach(System.out::print); Collections.reverse(simpsons); simpsons.stream(). forEach(System.out::print); } }. Note that we've overridden the compareTo() method and passed in If we try to pass a Simpson that does not implement Comparable , we will In the first sort() invocation, the array is sorted to: when I compare these franchise objects without the Collections.sort they compare correctly, However when I test using the Collections.sort like I have here I get an output like this: GA, 670.0, Roddy White GA, 560.0, Julio Jones IN, 1270.5, Andrew Luck IN, 950.0, T.Y. Hilton MD, 1210.0, Ray Rice SC, 740.0, Greg Olsen WA, 980.5, Alfred Morris


You're always returning 1 when the packetNum doesn't match because you're missing an 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;
}

It's also true, as other have pointed out, that subtracting them or using Short.compare would make this code more terse and readable.

Java ArrayList of Object Sort Example (Comparable And Comparator), We generally use Collections.sort() method to sort a simple array list. Bound mismatch: The generic method sort(List) of type Collections is not applicable for the arguments We are overriding compare method of Comparator for sorting. If compareTo() returns a negative integer, the object is less than the specified object. If compareTo() returns a zero, the object is equal to the specified object. If compareTo() returns a positive integer, the object is greater than the specified object. Here’s how we sort a List of Employee object using Comparable interface in Java:


Don't code what's already coded for you, use

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

Javadoc

Java Collections sort() - Sort List of Objects by Field, Learn to use Collections.sort() method to sort arraylist of custom objects in java All elements in the list must be mutually comparable and should not throw We may need to sort list of custom objects which have their own sorting logic. @ Override. public int compareTo(Employee o) {. return this .getId(). 1. Pass Comparator as argument to sort() method. Comparators, if passed to a sort method (such as Collections.sort (and Arrays.sort), allow precise control over the sort order. In the following example, we obtain a Comparator that compares Person objects by their age.


Comparable and Comparator in Java Example, Comparable and Comparator in Java are very useful for sorting the collection of objects. is overridden to print the user-friendly information about the Employee public String toString() Employee cannot be cast to java.lang. @Override public int compareTo(Employee emp) { //let's sort the employee based on an id in � We encountered an Exception. Look at the exception -- it says: "System.Invalid.Operation". That means Sort() method is only used to sort normal array list with "integers" or "string" types. But for sorting the complex types, it will not know which type to sort (Ex: EmpAge or EmpSalary). So we get an error, "invalid operation".


Java Collections sort(), Java Collections sort method, Java Collections.sort(), Java Collections sort example Hence, we can see that Collections.sort() has sorted the list of String in Lexical order. And it does not return anything. this.name=name; this.taste= taste; } @Override public int compareTo(Object o) { Fruit f = (Fruit) o; return this.id - f.id ; } }. Programmers frequently need to sort elements from a database into a collection, array, or map. In Java, we can implement whatever sorting algorithm we want with any type.


How to sort a List of objects using Comparator in Java, This class's implementor needs to override the abstract method compare() defined in Comparators, if passed to a sort method (such as Collections.sort ( and If two people have same age, their relative ordering in the sorted list is not fixed. 1. Sort ArrayList of Objects – Collections.sort( List ) It sorts the specified List items into their natural order. All elements in the list must implement the Comparable interface. All elements in the list must be mutually comparable and should not throw ClassCastException. This sort is guaranteed to be stable.