Java Trick: Double brace initialization

This is a trick I found from the Core Java™: Volume I—Fundamentals, Ninth Edition, 6.4.6. Anonymous Inner Classes.
import java.util.ArrayList;
import java.util.List;

public class TestArrayList {
 private String s1;
 private static String s2;
 public static void main(String[] args) {
  TestArrayList tl = new TestArrayList();
  tl.printList(new ArrayList(){
   {add("a"); add("b"); add(s2);}
   });

 }

 public void printList(/*only final variables are accessible to local inner classes*/final List sList){
  printDynamicList(new ArrayList(){{add(s1); addAll(sList);}});
 }
 public void printDynamicList(List dList){
  
 }
}
As shown in the above code:

  • As shown in the line# 10, you can add elements to the anonymous array: this is called Double brace initialization.
  • Again in the line# 16, in the double brace initialization, s1 is added to the array which is a property fo the outer class.
  • To add the parameter in line# 16, it should be final, this is the rule of local inner classes.
If you have more info please add to this blog.

Comments

Popular posts from this blog

Parse the namespace based XML using Python

How To: GitHub projects in Spring Tool Suite

EJB 3 JUnit testing with OpenEJB 3.1.4