Solved

How does this findMax method use comparator to find the largest object?

Posted on 2011-09-20
11
341 Views
Last Modified: 2012-05-12
My book is discussing function objects and it gave the code below as an example. I would like to know 3 things:

1. Can you explain to me how the Comparator argument is being used in line 6?

2. How come the method that is being implemented in line 15 is named "compare" and then when it is accessed in line 6 it is referred to as "compareTo"? I thought compareTo was part of the Comparable interface, which is not in the code below.

3. Is cmp the function object in this example?
public static <AnyType> AnyType findMax(AnyType [] arr, Comparator<? super AnyType> cmp)
    {
       int maxIndex = 0;
	
	   for(int i = 1; i < arr.size(); i++){
	      if(cmp.compareTo(arr[i], arr[maxIndex]) > 0){
	         maxIndex = i;
	      }
		  }
	   return arr[maxIndex];
   }

class CaseInsenitiveCompare implements Comparator<String>
{
   public int compare(String lhs, String rhs){
      return lhs.compareToIgnoreCase(rhs);
   }
}

class TestProgram
{
   public static void main(String [] args){
      String [] arr = {"ZEBRA", "alligator", "crocodile"};
	  System.out.println(findMax(arr, new CaseInsensitiveCompare()));
	}
}

Open in new window

0
Comment
Question by:shampouya
  • 9
  • 2
11 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 36569976

It uses compareTo method of String
because your AnyType is substituted by String here
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36569991
this method requires that second parameter would be of Comparator type
but this method does not in fact use that this parameter is of Comaprator type
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36570003
Comparator indeed needs to define
compare(T o1, T o2)
method and if you don't define it compiler would complain - that;s becuase you declared that you need
object of Comparator type

Howvere once method gets this argument of this type
it does not use this fact that it is of comparartor
type becuae method compareTo is not method of comparator
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 47

Expert Comment

by:for_yan
ID: 36570009
On the other hand as your  seciond parameter was is in fact a String
method compareTo(string) works and method findMax can use it
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36570042
But are you sure it really works?

This is a wierd method
cmp.compareTo(arr[i], arr[maxIndex]) 

Open in new window

- neirther Compatrator, nor Comparable - where is it defined?
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36570059

In fact this code does not even compile - so no sense to explain anything about it
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36570147
there were many compilation mistakes there, including misporints, etc.
The closest I could get is this code, which has just one
copilation error - and that is  that
method cmp.compareTo(AnyType, AnyType)
is not resolved

import java.util.Comparator;

class CaseInsensitiveCompare<AnyType> implements Comparator<AnyType>
{
   public int compare(AnyType lhs, AnyType rhs){
       return 1;
      //return lhs.compareToIgnoreCase(rhs);
   }
}

class TestProgram
{
   public static void main(String [] args){
      String [] arr = {"ZEBRA", "alligator", "crocodile"};
	  System.out.println(findMax(arr, new CaseInsensitiveCompare<String>()));
	}

    public static <AnyType> AnyType findMax(AnyType [] arr, CaseInsensitiveCompare <AnyType> cmp)
    {
       int maxIndex = 0;

	   for(int i = 1; i < arr.length; i++){
	      if(cmp.compareTo(arr[i], arr[maxIndex]) > 0){
	         maxIndex = i;
	      }
		  }
	   return arr[maxIndex];
   }
}

Open in new window


So those are some pieces form different examples, I guess,
it should not be understood literally
0
 

Author Comment

by:shampouya
ID: 36571996
This must be a typo in the book then. Your code works if you use compare instead of compareTo?
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36572117
Yes it works ths way - and prints the result :
ZEBRA



import java.util.Comparator;

class CaseInsensitiveCompare implements Comparator<String>
{
   public int compare(String lhs, String rhs){
      return lhs.compareToIgnoreCase(rhs);
   }
}

class TestProgram
{
   public static void main(String [] args){
      String [] arr = {"ZEBRA", "alligator", "crocodile"};
	  System.out.println(findMax(arr, new CaseInsensitiveCompare()));
	}

public static <AnyType> AnyType findMax(AnyType [] arr, Comparator<? super AnyType> cmp)
    {
       int maxIndex = 0;

	   for(int i = 1; i < arr.length; i++){
	      if(cmp.compare(arr[i], arr[maxIndex]) > 0){
	         maxIndex = i;
	      }
		  }
	   return arr[maxIndex];
   }


}

Open in new window

0
 

Author Comment

by:shampouya
ID: 36572173
Ok now that we know it works, I want to understand the main point of this program. Can you read below and tell me if I'm understanding correctly? Feel free to correct my wording.

The goal was to create a generic method called findMax, which would accept two parameters. It would accept an array of any type as it's first parameter. As its second parameter it would accept an object of a class that implements the Comparator<String> interface. Once the two arguments were sent to the findMax method, findMax would use the "compare" method from the second argument to compare each array element of the first argument. This was done with a for loop. Once the string with the highest value ("zebra") was found, then findMax would return that string value to the println method. Then println would print out "zebra". In this code, the second argument passed to findMax was new CaseInsensitiveCompare(), which is a class with no data and only one method, commonly known as a function object. The function object doesn't pass information, it merely passes the implemented ability to perform a method, which in this case is the "compare" method.
0
 
LVL 47

Accepted Solution

by:
for_yan earned 500 total points
ID: 36572385
I think this is correct.
One thing to put it more accurate - findMax is defined as generic method and it will acceot aarray of  any type as first parameter and an object of the class
which implemnets Comprarator<this same type>  (definition of the method findMax does not require comparator always with respect to String as a second
parameter; it requires comparator with respect to the type to which first parameter array belongs).
Other than that I think it all is fine. It is in this program that you use it for the String type, but it is defined more broadly
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
jdbc error in jsp application 20 71
eclipse buid path vs tomcat lib path 10 37
Java: anonymous class 4 37
Java array sort 10 26
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

679 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question