Solved

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

Posted on 2011-09-20
11
343 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

 
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

Industry Leaders: 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

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Suggested Courses

737 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