Wednesday, August 5, 2009

Using anonymous class in Java

The Java Language Specification, Third Edition
http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html

The Java Tutorials
http://java.sun.com/docs/books/tutorial/index.html

Java in a Nutshell
http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class TestAnonymous {

@SuppressWarnings("serial")
public static void main(String[] args) {

Map<Object, Object> map = new HashMap<Object, Object>() {

@SuppressWarnings("unchecked")
@Override
public Object put(Object key, Object value) {
if (containsKey(key)) {
((List<Object>) get(key)).add(value);
} else {
List<Object> list = new ArrayList<Object>();
list.add(value);
super.put(key, list);
}
return value;
}
};

map.put("k1", 1);
map.put("k1", 2);
map.put("k1", "1");
map.put("k1", "2");

map.put("k2", 1);
map.put("k2", "1");

map.put("k3", 1);

System.out.println(map.toString());


}

}



{k3=[1], k1=[1, 2, 1, 2], k2=[1, 1]}


Anonymous class converted to nested class
private static final class HashMapConvertList extends
HashMap<Object, Object> {
@SuppressWarnings("unchecked")
@Override
public Object put(Object key, Object value) {
if (containsKey(key)) {
((List<Object>) get(key)).add(value);
} else {
List<Object> list = new ArrayList<Object>();
list.add(value);
super.put(key, list);
}
return value;
}
}
...

Map<Object, Object> map = new HashMapConvertList();



No comments:

Post a Comment