You are here: Home ยป Initializing Java collections and arrays during creation

Initializing Java collections and arrays during creation

Posted on Saturday, March 15 2014 at 21:32 (Age: 5 yrs) | Category: Software Engineering, Java

Initializing collections with predefined values

Especially when writing unit tests or mock objects, it can be useful to initialize collections like Lists, Maps and Arrays with specific values. The usual way to do this is to instantiate the corresponding class and then add the values, e.g.


List<String> names = new ArrayList<>();
names.add("John");
names.add("Jack");
names.add("Greg");

However, when the collection is only required to be passed to a method as parameter, this adds a temporary reference variable to the current scope.

In another scenario, it could be necessary to create a collection with predefined values as class members, and using the approach above would require the add() calls to be done in the class constructor (or in the instance initializer). For readability and maintainability, it would be better to add the default values at the same place where the member is defined. In any case, initializing collections in this way can be done using the "double brace initialization syntax":


List<String> names = new ArrayList<String>() {{
      add("John");
      add("Jack");
      add("Greg");
   }};

Is this really a specific, probably new, Java syntax? Not really - lets rewrite it slighty:


List<String> names = new ArrayList<String>() {

   {
      add("John");
      add("Jack");
      add("Greg");
   }

};

It might be more obvious now - what we do is that we create an anonymous class as a sub class of ArrayList<String>. In that class, we create an instance initializer which is enclosed with the inner pair of braces. Syntactically this can be written as above, hence the name "double brace initializer". One particular detail to consider is that the diamond operator can not be used with anonymous classes, so we need to explicitly name the type when instantiating a generic class. See stackoverflow.com/questions/13821586/why-cant-diamond-infer-types-on-anonymous-inner-classes for more details. Using this approach also allows to pass a readily initialized collection as a parameter to a method, without the need to create a temporary variable as in our introductionary example:


   public void processMap(Map map) {
      System.err.println(map);
   }

   public static void main() {
       processMap(new HashMap<String, Integer>() {{
             put("one",  1); 
             put("two",  2); 
             put("three",  3); 
          }});
   }

Initializing raw arrays with predefined values

Another common use case is to create a raw array with predefined values. When T is the array type, then the syntax for array initialization is:


T[] array = new T[] {val1, val2, val3, ..., valN};

This creates an array with N elements, initialized with the given values. The nice thing is that this syntax can also be used to initialize an array while passing it as parameter. Consider the following method:


public void processArray(int[] array) {
   System.err.println(Arrays.toString(array));
}

Then, when we want to pass an array with the values 1, 2, 3, we can simply call the method like this:


processArray(new int[] {1, 2, 3} );

The same works also with reference type arrays:


public void processArray(Date[] array) {
   System.err.println(Arrays.toString(array));
}

processArray(new Date[] {new Date(123456789012L), new Date(234567890123L), new Date(345678901234L)} );

No comments

Be the first to post a comment!