Question about this chunk of Java Code

jinduy

Diamond Member
Jan 24, 2002
4,781
1
81
private static void printMap(Map map)
{
List list = new ArrayList(map.entrySet());
Comparator frequencyComparator = new Comparator()
{
public int compare(Object o1, Object o2)
{
Map.Entry entry1 = (Map.Entry)o1;
Map.Entry entry2 = (Map.Entry)o2;
Integer value1 = (Integer)entry1.getValue();
Integer value2 = (Integer)entry2.getValue();
return value2.compareTo(value1);
}
};

Collections.sort(list, frequencyComparator);
Iterator itor = list.iterator();
while (itor.hasNext())
{
Map.Entry entry = (Map.Entry)itor.next();
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}



what is the bold part of that function called? i've never seen a method being created immediately following an object declaration, nor have i seen a method being created within another method... i'm probably not even interpreting it correctly...

can someone explain what's going and how this works? Thanks... (btw i copied this code from java.sun.com
 

jinduy

Diamond Member
Jan 24, 2002
4,781
1
81
i think i sorta get it...
the creation of the Comparator instance also included overriding of the default compare(o1,o2) method... i've never learned this concept... does anyone know what this concept or type of programming is called? thanks!!!
 

akubi

Diamond Member
Apr 19, 2005
4,392
1
0
anonymous classes is the name you want.

basically, instead of the trouble of defining a new FrequencyComparator class that extends Comparator (just to overload compare()), you can create an anonymous class by simply overloading just the bits you want.