How to Write a Compareto Method Which Compares Objects

How do I write a compareTo method which compares objects?

This is the right way to compare strings:

int studentCompare = this.lastName.compareTo(s.getLastName()); 

This won't even compile:

if (this.getLastName() < s.getLastName())

Use
if (this.getLastName().compareTo(s.getLastName()) < 0) instead.

So to compare fist/last name order you need:

int d = getFirstName().compareTo(s.getFirstName());
if (d == 0)
d = getLastName().compareTo(s.getLastName());
return d;

How to use compareTo() to compare two objects?

Your class needs to implement Comparable interface, and inside your class you need to override compareTo method (which is in Comparable interface). In this method you will define how your object will be compared to another, on what 'criteria' the comparison will be done.

It's a good practice to implement compareTo method such that, when its return value is 0, it's like two objects are equals (e.g. firstK.compareTo(secondK) == firstK.equals(secondK)).

You can also read Java documentation compareTo documentation.

public class K implements Comparable<K> {
//Attributes, constructor etc
@Override
public int compareTo(final K otherK) {
/*
Do what you want to compare them, for example, if your
K class has a integer field 'value', and you want to compare
K's instances based on 'value' field, you can do as follow:
*/
return Integer.compare(this.value, otherK.getValue());
}
}

Java Use compareTo to Compare Two Objects

You are going to need something like this.

Object biggestObject = array[0];
for (Object obj: array){
if (biggestObject.compareTo(obj) == 1){
biggestObject = obj;
}
}
return biggestObject;

If you are using a custom object you are going to need to override the compareTo method so like if the object is a person and we are comparing Pen... feet size, then we would want to set up compareTo to compare feet sizes, returning 1 when the object being compared to is bigger, 0 if its the same, and -1 if its smaller.

@Override
public int compareTo(Object obj){
if (this.feetSize < obj.getFeetSize()){
return 1;
etc, etc....

Java compareTo method beginner level

sort the students based on the neptun code

Two parts. Part one, change

implements Comparable

to

implements Comparable<Student>

And then

@Override
public int compareTo(Student o) {
return this.nep_c.compareTo(o.nep_c);
}

However, you then say Within it, by the number of mark you get. so perhaps you really want

@Override
public int compareTo(Student o) {
return Integer.compare(getMark(), o.getMark());
}

If you mean to sort by neptun code, and use mark(s) as a tie-breaker then you could do something like

int c = this.nep_c.compareTo(o.nep_c);
if (c != 0) {
return c;
}
return Integer.compare(getMark(), o.getMark());

Or, in Java 8+, using Comparator.comparing like

return Comparator.comparing(Student::getNep_c)
.thenComparingInt(Student::getMark).compare(this, o);

Understanding syntax for compareTo() method in Java

The idea behind it is that compareTo doesn't return 0,1,-1, but returns 0 (equals), positive number (bigger than) or negative (smaller).

For that reason, simply subtracting the ages will give you the correct answer

how do you compare an object with a comparable?

Looks like x is your Comparable interface. You should call the compareTo method on this parameter, and then compare the result with 0. The Comparable Javadoc has some usage examples. The compareTo function returns:

a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

The reason you get your errors is that, at first, you were trying to apply the < on incompatible types. p.getValue() returns you an Object, while x is a Comparable (usually you should apply this operator on primitives, like int, long, etc.).

The second error was that, even if p.getValue() object has a compareTo method, you must be careful against which other object you compare to. For example, if it's a String, you can compare it only against another String, e.g., "str1".compareTo("str2");

In order to correctly compare your values, you should do something like:

// checking if x is less than p's value
if (x.compareTo(p.getValue()) < 0) { ... }

// checking if x is greater than p's value
if (x.compareTo(p.getValue()) > 0) { ... }

// checking if x is equal to p's value
if (x.compareTo(p.getValue()) == 0) { ... }

Java object comparison: implementing a `compareTo()` method for a playing card game

First of all, the purpose of the compareTo() method is to define what makes two objects comparable. Not all objects are comparable. Some objects are made comparable by the Java API. For example, String is comparable. So if you were to use a method such as Collections.sort(someStringArray), this task can be accomplished because the objects are comparable. On the other hand, if you wanted to sort() an array of your Card objects, it can't be accomplished until you make the Card object comparable. You do this by using the compareTo() method. You also want to define your Card class as implements Comparable interface, in which you will have to @Override the compareTo() method. This, will make your Cards comparable by rank, if you decide to compare them by rank in your compareTo().

What I believe you're trying to is compare the two objects by rank.

int turn = this.getRank().compareTo(player2.getRank());

is generally what throws me off. What exactly is the compareTo method doing?

You're comparing the rank of this, which I'm assuming is Player1 to the rank of player2. When you use the compareTo() method, you return an int. This int tells you which player's rank is higher... 1 meaning, player1's rank is higher, -1 meaning player2's rank is higher, and 0 meaning the ranks are equal. This int I'm assuming will determine whose turn it is

Also, I believe that this:

int turn = this.getRank().compareTo(player2.getRank());

should be placed outside of the compareTo() method and should be change to this:

int turn = this.compareTo(player2);

You're already comparing the players by their ranks in the compareTo(), so you don't need to use getRank(). I don't know if this will solve your problem completely, because I don't have your complete code, but I hope this gives you a better understanding of how the compareTo() method works.



Related Topics



Leave a reply



Submit