finding the largest object help
hi, i'm having trouble with this java programming problem. any help will be greatly appreciated :)
Write a method that returns the largest object in an array of objects. The method signature is:
public static Object max(Comparable[] a)
all the objects are instances of the Comparable interface. The order of the objects in the array is determined using the compareTo method.
Write a test program that create an array of ten strings, an array of ten integers, and an array of ten dates, and finds the largest string, integer, and date in the array.
*i think the compareto method is what is confusing me*
Re: finding the largest object help
Basically, the compareTo() method will return -1, 0 or 1. If the comparable object using this method is less than the comparable object in the parameters, it returns -1. If the comparable object using this method is equal to the comparable object in the parameters, it returns 0. If the comparable object using this method is greater than the comparable object in the parameters, it returns 1.
So, lets say we wanted to compare two number (this is not actual code and will not compile):
Code :
//Returns -1
4.compareTo(5);
//Returns 0
4.compareTo(4);
//Returns 1
4.compareTo(3);
Do you understand that much?
Re: finding the largest object help
Quote:
Originally Posted by
aussiemcgr
Basically, the compareTo() method will return -1, 0 or 1.
According to the Comparable API:
"Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. "
Re: finding the largest object help
It doesn't have to be -1, 0, or 1. It just has to fall into one of these three categories: less than zero, equal to zero, or greater than zero.
So using the compareTo() method, you're largest object compared to every other object will return a value greater than 0 (can you see why?)
Re: finding the largest object help
Quote:
Originally Posted by
helloworld922
It doesn't have to be -1, 0, or 1. It just has to fall into one of these three categories: less than zero, equal to zero, or greater than zero.
So using the compareTo() method, you're largest object compared to every other object will return a value greater than 0 (can you see why?)
Ya, you got me there. I'm just used to working with tiny numbers and I overlooked that, but you are entirely correct.