manbearpig1 manbearpig1 - 7 months ago 30
Java Question

Java Comparable interface: compareTo int attributes

Two objects of the same type each have int attributes called intValue. How can the Comparable interface be used to compare these two objects on the basis of their intValue int values?

public int compareTo(myObject other) {
return (this.intValue).compareTo(other.intValue);


This produces the error

error: int cannot be dereferenced


First make sure that your myObject class implements the Comparable interface:

public class myObject implements Comparable<myObject>

If you're deducing the value returned by compareTo using primitive int values, you could use the method:

public int compareTo(myObject other) {
    return, other.intValue);  

This is logically the same as using Integer.valueOf in conjuction with compareTo:

public int compareTo(myObject other) {
    return Integer.valueOf(this.intValue).compareTo(Integer.valueOf(other.intValue));