Double Brace Initialization in java

Spread the words...Share on Google+4Share on Facebook2Tweet about this on Twitter6Share on LinkedIn23Buffer this pageShare on StumbleUpon0Share on Reddit0

Don’t you feel that Java should have a more convenient syntax for collections (lists, maps, sets, etc.). The reason I am saying this is because every time if you have you use a collection in your code then every time you have to:

  1. Declare a variable for a temporary collection
  2. Create a new empty collection and store a reference to it in the variable
  3. Put things into the collection
  4. Pass the collection to the method

For example:

import java.util.HashSet;
import java.util.Set;

public class DoubleBrace {
	public static void main(String[] args) {
		Set<String> params = new HashSet<String>();
		params.add("param one");
		params.add("param two");
		params.add("param three");
		params.add("param four");
		// ... and so on; Now pass above collection as parameter to method or
		// some other ways
		useParamsInSomeMethod(params);
	}

	private static void useParamsInSomeMethod(Set<String> params) {
		// TODO Auto-generated method stub
	}
}

These are normal steps we all follow in our daily coding practices. Lets see another easy way of doing it. This is know as double brace initialization. The syntax to use this feature is as follows:

import java.util.HashSet;
import java.util.Set;

public class DoubleBrace {
	public static void main(String[] args) {
		Set<String> params = new HashSet<String>() {
			{
				add("param one");
				add("param two");
				add("param three");
				add("param four");
			}
		};
		// ... and so on; Now pass above collection as parameter to method or
		// some other ways
		useParamsInSomeMethod(params);
	}

	private static void useParamsInSomeMethod(Set<String> params) {
		// TODO Auto-generated method stub
	}
}

Or make it more simple:

import java.util.HashSet;

public class DoubleBrace {
	public static void main(String[] args) {

		useParamsInSomeMethod(new HashSet<String>() {
			{
				add("param one");
				add("param two");
				add("param three");
				add("param four");
			}
		});
	}
	private static void useParamsInSomeMethod(HashSet<String> params) {

	}
}

How it works

Lets understand how this works. The first brace creates a new Anonymous Inner Class. These inner classes are capable of accessing the behavior of their parent class. So, in our case, we are actually creating a subclass of HashSet class, so this inner class is capable of using add() method.

And second set of braces are nothing but instance initializers. If you remind core java concepts then you can easily associate instance initializer blocks with static initializers due to similar brace like struct. Only difference is that static initializer is added with static keyword, and is run only once; no matter how many objects you create.

Important points

  • As classes initialized this way are basically inner classes. So we can create them for all other classes until they are not final.
  • Such classes should not be used where equals() method is not explicitly modified to use them because mostly equals() method checks for class equality also.
  • You should always keep in mind that initializers are run before constructors (but not before super class constructors).
  • The instance of the anonymous class that you have created contain a synthetic reference to the enclosing object. If you serialize the collection you will also serialize everything in the outer class.

Happy Learning !!

Spread the words...Share on Google+4Share on Facebook2Tweet about this on Twitter6Share on LinkedIn23Buffer this pageShare on StumbleUpon0Share on Reddit0

 

 

Give me your email address and whenever I write any tutorial or discuss any java concept, you will receive a little email in your inbox.

Join 2,865 other subscribers

5 thoughts on “Double Brace Initialization in java”

  1. sir,
    i have a question.
    what is the difference between inner class and nested class and what is the need of inner class.why do we create inner class?

Want to ask any question? Or suggest anything?