Expression idiom for Java

November 17th, 2007

3 Responses to “Expression idiom for Java”

  1. Jason Says:
       Map map = new HashMap() {{
  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>();
            return Collections.unmodifiableMap(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