简体   繁体   中英

java comparable interface in sorting

I came up with the problem in sets is to build my own default sorting order using comparable interface. I want to arrange (int eid,String ename) in descending order based on eid only. So this was the logic I couldnt understand in the comapreTo method.

public class First implements Comparable<First> {

private final int eId;
private final String eName;

public First(int eId, String  eName){
    this.eId = eId;
    this.eName = eName;
}

public int getEId() {
    return eId;
}

public String toString(){
    return eName + "------" + eId;
}

public int compareTo(First obj){
    int eId1 = this.eId;
    First f = (First) obj;
    int eId2 = f.eId;
    if (eId1 < eId2){ 
        return -1;
    } else if (eId1 > eId2){
        return +1;
    } else {
        return 0;
    }
}}

please explain how this works and is there any other way of implementation?

As I haven't seen you express understanding to the part of your question which asks "how it works" I guess you still might not be clear on that end. I see you don't understand the "logic" behind some of the code based on your comments in some of the answers too.

We will take the example given by Mark Rotteveel to explain the logic as I believe that was a decent way to implement compareTo .

public int compareTo(First other){
if (eId < other.getEId()){ 
    return -1;
} else if (eId > other.getEId()){
    return +1;
} else {
    return 0;
}
}

We have the method compareTo take in a parameter which is an object of the type First - which is the class you created. This type includes all the properties that you have included in this class, for example having a getEId method that allows you return the private global variable eId that you find within your class First .

Now the thing is this other parameter in the compareTo is it's own instance of a First object, and not the same one you are comparing with inside the compareTo method (this part: if (eId < other.getEId()) ).

Inside the compareTo method we use a if-else statement to check if eId (which refers to your current global variable eId ) to the eId that was created for the First object that was passed as an argument to the compareTo method. So these two are not the same value .

As you said you are new to programming think of it this way, you made a class First that has a constructor:

public First(int eId, String  eName){
this.eId = eId;
this.eName = eName;
}

You can then make two different First objects as such:

First obj1 = new First(5, "Object 1");
First obj2 = new First(12, "Object 2");

In this example obj1 and obj2 are not the same object, and inherently have different eId values. The one you pass into the compareTo method might be obj2 for example, which would be different from the eId that it's currently comparing to.

So when we pass obj2 into the method like this compareTo(obj2) , this would mean that when it reaches the part of the code that reads other.getEId it would perform obj2.getEId which would obviously return a different eId than the eId inside the if statement. In this example ' obj2.getEId ' it would return the integer 12, because as you see I set eId as 12 for obj2 earlier.

The rest of the code in the if-else statement is pretty straightforward, if the eId you are currently comparing with is of lesser value in terms of an integer, return -1 , else if its greater return +1 to move it up or down to sort them according to their eId . Return 0 in any other case because in that case they would be equal in terms of eId .

I hope that clarifies the code a bit in terms of the logic behind things and how the instances of eId compared within compareTo are different.

The equals method and == and != operators test for equality/inequality, but do not provide a way to test for relative values. Some classes (eg, String and other classes with a natural ordering) implement the Comparable interface, which defines a compareTo method. You will want to implement Comparable<T> in your class if you want to use it with Collections.sort() or Arrays.sort() methods.

Your comparison method is lacking, a proper example would be:

public int compareTo(First other){
    if (eId < other.getEId()){ 
        return -1;
    } else if (eId > other.getEId()){
        return +1;
    } else {
        return 0;
    }
}

By typing the Comparable interface, you can tell what kind of data gets compared. This ensures proper comparisons. Your example could run into a NullPointerException really quickly.

please explain how this works

I guess your question is basically,

Why do I need to implement the comparable interface to sort a list?

To sort a list, you first need to tell Java how to compare two objects. This way, Java can figure out which object is "less" and which is "greater". Using this information, the list can then be sorted in an ascending order, or a descending order.

How do you tell Java which is greater and which is less?

If this is greater than the other argument, return 1. If this is less than the other argument, return -1. Otherwise, return 0.

is there any other way of implementation?

Actually, your current compareTo method doesn't compile. A better implementation would be:

public int compareTo(First other){
    return Integer.compare(this.getEId(), other.getEId());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM