0

I am given an assignment to sort an array of inputted values using both insertion sort and selection sort. I am having some trouble with overwriting the compareTo method with in the Item class. I would like it to sort so that if two items are priced the same it then compares based on Category. So Child (C) items come first and then M and then Women. This is my code and every time that I attempt to compile it I get an error saying that double cannot be referenced.

public int compareTo (Object other) {
      int result;

      double otherPrice = ((Item)other).getClothPrice();
      String otherCategory = ((Item)other).getClothCategory();

      if (clothPrice == otherPrice)
         result = clothCategory.compareTo(otherCategory);
      else
         result = clothPrice.compareTo(otherPrice);

      return result;
}

1 Answer 1

7

First, your compareTo method should take an Item as a parameter. If this results in a compiler error, make sure Item is implementing Comparable<Item>.

To compare primitive double values, use Double.compare:

public int compareTo(Item other) {
    int result = Double.compare(clothPrice, other.clothPrice);
    if (result == 0) {
        result = clothCategory.compareTo(other.clothCategory);
    }
    return result;
}

If you're using Java 8, you may prefer to use some of the more advanced features of Comparator which make extending this code much simpler:

private static final Comparator<Item> naturalOrdering = Comparator
        .comparingDouble(Item::getClothPrice)
        .thenComparing(Item::getClothCategory);

public int compareTo(Item other) {
    return naturalOrdering.compare(this, other);
}
Sign up to request clarification or add additional context in comments.

5 Comments

I was forgetting to add the Comparable, thank you for that I ended up getting the code to work by just changing the else to result = Double.compare(clothPrice, otherPrice); Would that accomplish the same thing?
@TommyHarvey Yes, that would accomplish the same thing. I've just rewritten your code in the way I've seen most people write it.
Ok thank you I was just going off the example we were given in class. Thank you very much for your help
Wow, I didn't know about Comparator. Thanks! Shouldn't that Comparator object be cached for the sake of performance rather than re-instantiated on each call to compareTo?
@BasilBourque Yes, it would be much more efficient to cache the Comparator object using a static field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.