?
Solved

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

Posted on 2011-09-20
11
Medium Priority
?
348 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
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
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 2000 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

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses
Course of the Month14 days, 2 hours left to enroll

801 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