Solved

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

Posted on 2011-09-20
11
333 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
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
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

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Suggested Solutions

Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
The viewer will learn how to implement Singleton Design Pattern in Java.

757 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

23 Experts available now in Live!

Get 1:1 Help Now