Java Double Brace Initialization

Java double brace initialization is referred as to create and initialize the objects in single step, which normally is done in multiple steps. They are done using double curly braces.

1. Create and initialize object without double brace

Don’t you feel that Java should have a more convenient syntax for collections (List, Map, Set, etc.). The reason I am saying this is because every time if we have to use a collection in our code then we have to perform following actions-

  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 WithoutDoubleBrace 
{
	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 realtime coding practices.

2. Double brace initialization to create and initialize object in ‘single step’

Lets see another easy way of doing it. This is know as double brace initialization. The syntax to use double brace 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
	}
}

2.1. Inline double brace initialization

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) {
		//perform some operation
	}
}

3. How double brace initialization 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.

4. Summary

  1. As classes initialized with double braces are basically inner classes. So we can create them for all other classes until they are not final.
  2. 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.
  3. You should always keep in mind that initializers are run before constructors (but not before super class constructors).
  4. 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.

5. Java 9 factory methods

Java 9 has brought a lot of factory methods which can be used to create and initialize the Java collections in single statement. It can be an alternative, and preferred approach if you are using Java 9 or later. It eliminates the necessity of double brace initialization.

List<String> names = List.of("lokesh", "rohit", "alex");

Set<String> names = Set.of("Lokesh", "Amit", "John");

Map<String, String> names = Map.ofEntries(
				                Map.entry("1", "Lokesh"),
				                Map.entry("2", "Amit"),
				                Map.entry("3", "Brian"));

6. Java 8 stream collectors

For Java 8 and lower versions, you can find similar use cases in form of Java streams.

Set<String> names = Stream.of("lokesh", "rohit", "alex")
      				.collect( collectingAndThen( toSet(), Collections::unmodifiableSet ) ); 

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

3 thoughts on “Java Double Brace Initialization”

  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?

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.