Tuesday, January 25, 2011

Block initialization of Java variables

Java provides a number of ways to initialize variables. Initializing complex data structures like lists and maps in Java could be tedious but there is a nicer way to do that through the inline initialization using a block. The block here is similar to the static block, but without the static keyword. For example:
 

String[] stringList=new String[10];
...
List list=new ArrayList(){{
for(int i=0; i<stringList.length; i++){
add(stringList[i]);
}
}};

this initializes a static ArrayList defined in a class by adding a list of strings also defined inside the class. However the strange thing is when a block is used to initialize variables inside a method environment, the variables used to initialize must have been declared final. For example:

    public int someFunction(final String[] stringList)    {

        List<String> list = new ArrayList<String>(){{
            for(int i=0; i<stringList.length; i++){
                add(stringList[i]);
            }
        }};
    }

Using non-final variables for instance initialization does not work. In the next post, I will try to post more on final, subclassing and method overriding using final.

No comments:

Post a Comment