Search code examples
javacastingcomparablecompareto

Using a method after casting in Java


I have written the code:

public int compareTo(Object w) {
    //w = (Word)w

    if(this.count > (Word) w.getCount()) {
        return -1;
    } else if (this.count < (Word) w.getCount()) {
        return 1;
    } else {
      return 0;
    }
}

I have written the class Word. It implements Comparable so I must use the Object parameter for the compareTo() method.

However, I need the object to use a method in the Word class. I get an error if I cast and was wondering if I am doing something wrong or if I need to try something else?

Word class:

package comp10152_lab3;

public class Word implements Comparable{
private int count;
private String word;

public Word(String word) {
    this.word = word;
    this.count = 1;
}


public int getCount() {
    return count;
}

public void setCount(int count) {
    this.count = count;
}

public String getWord() {
    return word;
}

public void setWord(String word) {
    this.word = word;
}

@Override
public int compareTo(Object w) {
  if(this.count > w.getCount()){
    return -1;
  }
  else if (this.count < w.getCount()) {
    return 1;
  }
  else {
      return 0;
  }

}

public void countUp() {
    count++;
}

@Override
public String toString() {
    return word + "(" + count + ")";
}

@Override
public boolean equals(Object w) {
    return w.equals(word);
}


}

The equals class is suppose to be that way, as per instruction. The error I am getting is on the w.getCount() which is a "missing symbol" error.


Solution

  • This is the code that you need:

    public int compareTo(Object o) {
      Word w = (Word) o;
      if(this.count > w.getCount()){
        return -1;
      }
      else if (this.count < w.getCount()) {
        return 1;
      }
      else {
          return 0;
      }
    }
    

    The problem that you were having was due to the fact that w was of the type Object, the statement w = (Word) w would not do what you wanted. The second part of the problem has to do with the precedence of the cast operator in Java. When you do (Word)w.getCount(), the getCount() part gets evaluated first, meaning that you were effectively doing (Word) <some int>. What you could have done was wrap it in parentheses like ((Word) w).getCount() to solve that problem.