Don't understand this generic method
I am working through the O'Reilly book "Java Generics and Collections". In the "Comparison and Bounds" chapter, they provide an example method that takes a Comparator of a given type as an argument, and returns a Comparator of alist of that type. here's the code:
import java.util.*;
publicclass Test{
publicstatic <E> Comparator<List><E>> listComparator(final Comparator<E> cmp){
returnnew Comparator<List><E>>(){
publicint compare(List<E> list1, List<E> list2){
int n1 = list1.size();
int n2 = list2.size();
for (int i = 0; i < Math.min(n1, n2); i++){
int k = cmp.compare(list1.get(i), list2.get(i));
if (k != 0)return k;
}
return (n1 < n2) ? -1 : (n1 == n2) ? 0 : 1;
}
};
}
}
I'm trying to understand how this method works... I think maybe there are some language components/rules in use here that i'm just not familiar with. Anyway, the part that has me scratching my head is the nested compare method - where are the list1 and list2 arguments coming from? Can anyone break down for me line by line what is going on here? Thanks in advance!
I think you are not familiar with anonymous classes, right? That's what's happening there.
Here's a trivial example. Does it make sense?
interface Operator {
double op(double x, double y);
}
//elsewhere:
public Operator createOperator() {
return new Operator() {
public double op(double x, double y) {
return x + y;
}
};
}
Message was edited by:
ParvatiDevi
ok... yep, i'm not familiar with anonymous classes yet. Is there any reading you would suggest on the topic?
Still confusing to me, though, is where the list1 and list2 parms are coming from. I mean, you would call the listComparator method, right? And you would supply a Comparator object... so, where do the args for the compare method come from? Am I missing something? Would the call to the method actually be more than invoking
listComparator(cmp)
?
Thanks
Here's one description of anonymous classes:
http://math.hws.edu/javanotes/c5/s7.html
I can't find much on anonymous classes in Sun's tutorials. They seem to
lump them into GUI code instead of presenting them on their own.
> Still confusing to me, though, is where the list1 and list2 parms are coming from
When you define a method, where do the method's parameters come from?
The answer to that is there are two destinct activities going on there, defining a method (1) and using it (2). Let me fill out my previous code into something that can be copied and run.
interface Operator {
double op(double x, double y);
}
public class AnonymousExample {
public static Operator createOperator(final double z) {
return new Operator() {
public double op(double x, double y) {
return x + y + z;
}
};
}
public static void main(String[] args) {
Operator f = createOperator(10);
System.out.println(f.op(20,30));
}
}
As you see, when I call op, I supply the values 20 and 30 for x and y.