0

I'm trying to sort an arrayList with a object I created called TextObject. I'd like to sort the arrayList is ascending value, based on a double value stored in the TextObject. I am able to make a comparable for int but struggling with doubles.

Here is my textObject code implementing Comparable:

public class TextObject implements Comparable<TextObject> {
private String line = "";
private int lineNum = 0;
private double score;

/**
 * constructor to build TO
 * @param lineScore
 * @param line
 * @param lineNum
 */
TextObject(String line, int lineNum){
    //this.lineScore = lineScore;
    this.line = line;
    this.lineNum = lineNum;
}


/**
 * to string method to print it out
 */
@Override
public String toString() {
    return "TextObject [line=" + line + ", lineNum=" + lineNum + ", score=" + score + "]";
}

@Override
public double compareTo(TextObject comparestu) {
    double compareScore=((TextObject)comparestu).getScore();
    return this.score-compareScore;
}


/**
 * @return the score
 */
public double getScore() {
    return score;
}
}

Then I'm calling the arrayList using Collections.sort from another class:

     Collections.sort(st.getLinesArr());
     for(TextObject to : st.getLinesArr()){
        System.out.println(to);
   }

I'd like help with the comparable method.

halfer
  • 19,824
  • 17
  • 99
  • 186
Katie Melosto
  • 1,047
  • 2
  • 14
  • 35
  • The compareTo() method is supposed to return an int, not a double. The compiler error message tells it to you. Read the message. It makes sense. You can compare doubles using Double.compare(). Or simply by reimplementing it, by testing if the first double is bigger, equal or lower tha the second one. – JB Nizet Nov 28 '19 at 18:01
  • This won't compile: `public double compareTo(TextObject comparestu) {` since the method ***must*** return an int. Try `return Double.compare(x, y);` – Hovercraft Full Of Eels Nov 28 '19 at 18:01
  • @JBNizet ok. Thanks for the feedback. I'll work on this – Katie Melosto Nov 28 '19 at 18:03
  • 1
    Note that you probably shouldn't implement Comparable in the first place. Just because two text objects have the same score doesn't mean that they are equal. And compareTo() should be consistent with equals(). Use a comparator to sort the list. – JB Nizet Nov 28 '19 at 18:03
  • @HovercraftFullOfEels thanks so much. I'll try this out – Katie Melosto Nov 28 '19 at 18:03

0 Answers0