Tags

Expression idiom for Java

November 17th, 2007

3 Responses to “Expression idiom for Java”

  1. Jason Says:
       Map map = new HashMap() {{
            put(1,2);
            put(3,4);
        }};
    
  2. friedrich Says:

    a Java 5/6 version:

        final Map<Integer,Integer> bar = new Object() {
        Map<Integer,Integer> map() {
            Map<Integer,Integer> map = new HashMap<Integer,Integer>();
            map.put(1,2);
            map.put(2,3);
            return Collections.unmodifiableMap(map);
        }}.map();
    
  3. carsten Says:

    Nice one, Jason! For all the others out there: This is an instance initializer, they are executed after the super and before the rest of the constructor. Short solution for cases where you can instanciate the required type directly. Thx, Jason

    My example code had been Java 5 actually, but the < and > got lost - put(1,2) won’t work otherwise of course, I’ll correct the post.

Leave a Reply