Comparator compare method() int cannot be dereferenced

14,623

Solution 1

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

Solution 2

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.

Solution 3

int being a primitive is not an object and thus does not have any methods. So when you try and call .compareTo on it, you get an error.

To compare ints, you can use the standard comparison operators < > ==, or you could wrap it in an Integer Object and use the compare method as you are doing now. Although the former is favorable.

Solution 4

// If Person.getName() returns a string then you could simply do the following to // implement Comparable:

public class PersonNameComparator implements Comparator<Person>{
   public int compare(Person p1, Person p2) {
    return p1.getName() - p2.getName();       // It's the ninja way to do it
   }
}
Share:
14,623
user2291903
Author by

user2291903

Updated on June 04, 2022

Comments

  • user2291903
    user2291903 almost 2 years

    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?

  • Tom
    Tom over 8 years
    "If Person.getName() returns a string then you could simply do the following to ..." create a compile time error.