Computer Science Canada

CompareTo method

Author:  phunkypants [ Fri Apr 02, 2010 6:10 pm ]
Post subject:  CompareTo method

Hey peeps. I'm trying to use compareTo to compare two integers (frequency) together.
Any help on how I can do this? I tried but I got an error (see below). I think I have to
change something in the parameters but I'm not sure what.

public class FrequencySorter implements Comparable<FrequencySorter>{

private String letters;
private int frequency;

public FrequencySorter(){
letters = "";
frequency = 1;
}
public FrequencySorter(String newLetters, int newFrequency){
this.letters = newLetters;
this.frequency = newFrequency;
}
public String getLetters(){
return letters;
}
public int getFrequency(){
return frequency;
}
public void setLetters(String newLetters){
this.letters = newLetters;
}
public void setFrequency(int newFrequency){
this.frequency = (newFrequency);
}
public String toString(){
return ("("+frequency + ") " + letters);
}
public boolean equals(FrequencySorter other)
{
return (letters == other.letters) &&(frequency == other.frequency);

}

public int compareTo(FrequencySorter obj){
return this.getFrequency().compareTo(obj.getFrequency()); //error: Cannot invoke compareTo(int) on the primitive type int
}
}

Author:  Tony [ Fri Apr 02, 2010 6:15 pm ]
Post subject:  RE:CompareTo method

read the error message.

You might be looking to use an Integer instead of int. Has the difference between objects and primitive types been explained to you? Method vs. Function vs. Operator?

Author:  phunkypants [ Fri Apr 02, 2010 7:02 pm ]
Post subject:  RE:CompareTo method

I changed frequency to an Integer and my program compiles now. Thanks for the help - I didn't realise there was such thing as an Integer object


: