• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Question about this chunk of Java Code

jinduy

Diamond Member
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
 
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!!!
 
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.
 
Back
Top