Im trying to use the compareTo() method to get the largest object in the array. The output I get is this:
Position of max area is...3
[Circle Color: null Filled: false 1.0, Circle Color: red Filled: true 1.0, Rectangle Color: null Filled: false 20.0 10.0, Rectangle Color: null Filled: false 5.0 1.0]
[Circle Color: null Filled: false 1.0, Rectangle Color: null Filled: false 20.0 10.0, Rectangle Color: null Filled: false 5.0 1.0, Circle Color: red Filled: true 1.0]
I now am able to get the right max are value, but I seem to be sorting it wrong
Thanks for the help in advance.
David Laverdy wrote:Im trying to use the compareTo() method to get the largest object in the array...
Well, I suspect that's your problem; unless ALL your GeometricObject classes are Comparable by area (and would that be "max" area?).
Have you considered a Comparator (java.lang.Comparator) instead?
PS: I've also broken up your LongLines (←click). Please try to avoid them.
David Laverdy wrote:This is for a homework assignment and we specifically need to use compareTo(). All of the objects have a area, I can get it to return the one with the largest area. Where is it failing when the sort method works down the array?
OK, well you appear to be trying to implement a recursive version of a bubble sort - why, I'm not quite sure - but simply put, it won't work.
I suspect you may have intended a selection sort, but that won't work without an iteration through ALL "remaining" elements.
Also, it's a horrible use of recursion (unless, that was also a requirement).
There's even a built-in method to do this for you, but I'll assume you're not allowed to use that.
(I was about to say that you should be checking for compareTo(...) < 0, not == -1, but it looks like that's been fixednow).
David Laverdy wrote:My teacher
Right, so we now have two requirements that you didn't explain at the start:
1. You must use the class's natural order.
2. You must use recursion for your sort method.
Unless your teacher also requires that the sort is stable, I suggest you look at the Quicksort algorithm.