• Post Reply Bookmark Topic Watch Topic
  • New Topic

A method that returns the largest object in an array of objects.  RSS feed

 
Alisha Hager
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everyone! This is my first time using this forum so I hope I am doing it right. This is what I have to create:
Write a method that returns the largest object in an array of objects. The method signature is:

public static Object max(java.lang.Comparable[] a)

All the objects are instances of the java.lang.Comparable interface. The order of the objects in the array is determined using the compareTo method.

Write a test program in the main method that creates an array of ten Strings, an array of ten Integers, and an array of ten java.util.Dates, and finds the largest string (i.e. in the alphabetical order), Integer, and Date in the arrays.

Name your java class Max and your java file Max.java.

I am struggling a bit with this code as I am sure you can see, and am at loss. I have never used the compareTo method. Am I doing this right, or on the right track with my code? Any help would be greatly appreciated.
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alisha Hager wrote:
Am I doing this right, or on the right track with my code? Any help would be greatly appreciated.


Why don't you test it? You created the max() method. You created a bunch of comparable arrays. Why not just call the method with those comparable arrays -- and see if the returned result is correct?

Henry
 
Alisha Hager
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry, Thanks for the reply. I do have one question. At the top did I implement Comparable correctly into my class? Because Max is underlined in red and I am not sure why.
This is the part I am talking about:

public class Max implements Comparable{
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alisha Hager wrote:Henry, Thanks for the reply. I do have one question. At the top did I implement Comparable correctly into my class? Because Max is underlined in red and I am not sure why.


I am assuming you are using an IDE? If so, then you should be able to get a tooltip over the red mark... along with options to automatically fix the issue.

Henry
 
Alisha Hager
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, I am using Eclipse. Ok, when I ran my mouse over "Max" at the top it told me to "Add unimplemented methods" just like you mentioned as well. So I did and it is still not compiling. This is what my code looks like now:

 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

First of all, why is the Max class Comparable? Are you even creating any Max instances?

Second, the description "still not compiling" isn't very helpful is it? ...

Henry
 
Alisha Hager
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Correct me if I am wrong, because I may be but I thought when one used the compareTo method they have to implement the Comparable interface.
 
Paul Clapham
Sheriff
Posts: 22844
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, you can call a method anything you like. There's no restriction at all. So you can call a method compareTo() if you like, even if you aren't implementing the Comparable interface. This might be confusing to readers of your code, but it's legal to do it.

On the other hand if you implement Comparable, then you do have to provide a method named compareTo() -- as you already know.
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alisha Hager wrote:Correct me if I am wrong, because I may be but I thought when one used the compareTo method they have to implement the Comparable interface.
It's the other way round. If you claim to implement the Comparable<T> interface you must write a method compareTo(T).
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can we do it with a Stream? Would this work (java8 only)?
Arrays.stream(myArray).max();
 
Liutauras Vilda
Sheriff
Posts: 4928
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alisha Hager wrote:Yes, I am using Eclipse. Ok, when I ran my mouse over "Max" at the top it told me to "Add unimplemented methods" just like you mentioned as well. So I did and it is still not compiling.

Maybe at the very beginning would be better to use something easier (simple text editor + command line compiler) rather than full of clever options IDE, which probably doesn't let you concentrate on Java programming language itself. IDE's suggestions could be very useful, in fact, you need to understand their meaning first. Just insert suggested code lines and try to compile probably it is not the best option when you learning how to program. You might thinking different at the moment, but it is worth to stay away from IDE's for now.
You could find more about them in "FAQ" section, can't remember exact link.
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alisha,

A few things to clarify:

1. The last code you gave does, in fact, compile. It compiles with a few warnings about raw types but that's not a biggie.

2. Your code will produce a runtime error, specifically a NullPointerException, when you run it.

3. Your Max class does not have to implement Comparable since there is really no logical way to compare one Max instance with another Max instance. There's no logical ordering to these objects since it doesn't represent a value. It's pretty much what we call a "utility" class that just provides some calculation or behavior. You can remove the implements Comparable in your class signature and remove the compareTo method that you implemented.

Getting back to #2:

If you read the JavaDoc for Comparable, you'll find that it says "Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false."

Since variable tempObj is null in the first iteration of the for-loop, passing it to compareTo() on line 7 will result in a NullPointerException being thrown.

For problems like this, it's best to assume that the first element, a[0], is "it", whatever "it" may represent. In this case, "it" is the object that is larger than all the other objects in the collection. You will then correct this assumption as you iterate through the rest of the array and determine otherwise.

As for your logic, it is flawed. Ignoring the problem with passing null to compareTo that I already pointed out, your code essentially says this:

Part of the problem here is the name you chose, tempObj. It's not a very good name because it doesn't "say" what it's for; i.e. it doesn't convey its purpose in the program. The name just indicates that it's some kind of temporary object, which doesn't really help explain what you're trying to do with it. It might as well be named whatever.

If you give it a better name, like theBiggestThingFound, then your code will be more expressive. I'm just using that now because it really stands out. If you plug that name back into the pseudocode above, it looks like this:

With this, it's pretty easy to see that the flaw in the logic is on line 7. Is it correct to say that the next element in the array is the biggest thing you've found? What if the array you're searching was {7, 5, 1, 3, 2, 4}? Let's say you know that the biggest you've seen so far is 7. When you compare 7 with 5, is it right to say that the biggest so far is now 1, the element after 5? What happens when you get to the end of the array? If you reference an element that's not there, you'll also get an error, specifically an ArrayIndexOutOfBoundsException.

Do you even need an else part here? The logic should be something like this:
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, a few more problems with the last code that you posted:

1. Look carefully at the signature of your main method. It's missing something. Compare it with the main example here: https://docs.oracle.com/javase/tutorial/getStarted/application/

2. How many elements does the array that you declare on line 21 have? This will cause an ArrayIndexOutOfBoundsException right off the bat when you run this program.

3. As already mentioned before, Edit: It looks like nobody else mentioned it after all. Anyway, your main doesn't do anything that will cause the code in the max() method to execute.
 
Darryl Burke
Bartender
Posts: 5167
11
Java Netbeans IDE Opera
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Can we do it with a Stream? Would this work (java8 only)?
Arrays.stream(myArray).max();

That returns an Optional, so you would need one more call to get a Max.Or, if returning null for an empty array is desired (instead of to throwing a NoSuchElementException):
 
Paweł Baczyński
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I suggest you shuffle the values in your test arrays.
Having sorted test arrays might give you false assurance that your method works correctly in case there is a problem in your algorithm.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!