1.

Explain the term “Double Brace Initialisation” in Java?

Answer»

This is a convenient means of initializing any collections in Java. Consider the below example.

import java.util.HashSet;import java.util.SET; public class IBDoubleBraceDemo{ public static void main(String[] args){ Set<String> stringSets = NEW HashSet<String>() { { add("set1"); add("set2"); add("set3"); } }; doSomething(stringSets); } private static void doSomething(Set<String> stringSets){ System.out.println(stringSets); }}

In the above example, we SEE that the stringSets were initialized by using double braces.

  • The first brace does the task of creating an anonymous inner class that has the capability of accessing the parent class’s behavior. In our example, we are creating the subclass of HashSet so that it can use the add() method of HashSet.
  • The second braces do the task of initializing the instances.

Care should be taken while initializing through this method as the method involves the creation of anonymous inner classes which can cause PROBLEMS during the garbage collection or serialization processes and may ALSO result in memory leaks.



Discussion

No Comment Found