I'm doing some assignment work and I've struck a problem.
I've been given this example code:
public class PersonNameComparator implements Comparator<Person>{
public int compare(Person p1, Person p2) {
int retValue = p1.getName().compareTo(p2.getName());
if (retValue != 0)
return retValue;
else if (p1.getAge() < p2.getAge())
return -1;
else if (p1.getAge() > p2.getAge())
return 1;
else
return 0;
}
}
However, when I try to do this, this happens:
public class DVDComparator implements Comparator <DVD> {
public int compare(DVD d1,DVD d2)
{
int stars1 = d1.getNoOfStars().compareTo(d2.getNoOfStars());
//ERROR - int cannot be dereferenced.
Any ideas?
You get this error message since getNoOfStars() returns a primitive int and there is no method compareTo() defined for primitive types.
If you're using Java SE 7 you can use something like this:
public class DVDComparator implements Comparator <DVD> {
public int compare(DVD d1,DVD d2){
return Integer.compare(d1.getNoOfStars(), d2.getNoOfStars());
}
}
You don't need to call a method to compare primitive ints. In fact, as you've discovered, you can't.
Just use the normal <, >, and == operators to compare ints.
Just make sure to follow the contract of compare -- return an int less than 0, equal to 0, or greater than 0, if d1 is "less than" d2, if d1 is "equal to" d2, or d1 is "greater than" d2, respectively.
Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With