Winston Gutkowski wrote:and the reason for doing it that way is that then both methods use the same "comparison" code, and therefore must be consistent.
Campbell Ritchie wrote:I am still dubious that Product in this case has a natural ordering. You can order products by price or by ID, so they don't have one natural ordering.
Winston Gutkowski wrote:I don't think you quite understand the idea of an 'order'.
Basically, what compareTo() (or, as Campbell suggested, a Comparator) does is to provide a way of deciding whether one object is "greater than", "less than", or "equal to" another object of the same type. And you do it so that you can sort them in a predictable way.
And usually - not always, but most of the time - it will be closely related to equals(), and involve comparing the same fields.
This is called "making comparison consistent with equals()", and is usually a good thing.
"I would say that an object should implement Comparable if that is the clear natural way to sort the class, and anyone would need to sort the class would generally want to do it that way.
If, however, the sorting was an unusual use of the class, or the sorting only makes sense for a specific use case, then a Comparator is a better option."
Campbell Ritchie wrote:λ
Hope you're enjoying the ride. :-)
Right now, you can create two Products with the same number, but different prices, but they will compare as equal, simply because their numbers are the same.
and those first two checks are important - especially the second one. And they're needed because equals() takes an Object, not a Product. The first one simply says, 'if o is the same object as me, we must be equal', and bypasses a lot of unnecessary logic. The second one says 'if o is not the same type as me, we cannot be equal', and is absolutely required. The rest is hopefully obvious.
@Louis - Does yours?
the last five lines of which can be reduced to:
return diff > 0.0d ? 1 : diff < 0.0d ? -1 : 0;
Campbell Ritchie wrote:
The bad news is, your assignment appears only to test your knowledge of switch statements.
Didn't I give you a Java™ Tutorials link yesterday? Have you read it?
Campbell Ritchie wrote:They have given you some good advice on SO. Parallel arrays are awkward to implement and error‑prone; you are far better creating an object that encapsulates the data you want to anaylse. Then you can put them into an array.
Campbell Ritchie wrote:Another thing: you will have to work out how to sort the array. Start by deciding what you are going to sort by. I don't think your products have a natural ordering, otherwise yo uwould make them implement
Only when you have got Product working should you write any other code. I can't understand your yoyo class; I think you may end up getting rid of all that code.
Why have you got a no‑arguments constructor?