Solved

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

Posted on 2011-09-20
11
336 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
 
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
create a gui in perl 3 70
Java Timer (static) 9 36
session migration servlets 2 24
How to convert String matching to regex in java 4 16
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
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…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

914 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now