Initialize a Collection

From CodeCodex

Implementations[edit]

Java[edit]

The regular way

 import java.util.List;
import java.util.ArrayList;
public class InitCollections {
  public static void main(String args[]) {
    ArrayList<String> list = new ArrayList<String>();
    list.add("Bart");
    list.add("Lisa");
    list.add("Marge");
    list.add("Barney");
    list.add("Homer");
    list.add("Maggie");
    dump(list);
  }
  
  public static void dump(List<String> list) {
    for (String s:list) {
      System.out.println(s);
    }
  }
}

Using a static initializer

 import java.util.List;
import java.util.ArrayList;
public class InitCollections {
  static ArrayList<String> list = new ArrayList<String>();
  
  static {
    list.add("Bart");
    list.add("Lisa");
    list.add("Marge");
    list.add("Barney");
    list.add("Homer");
    list.add("Maggie");
  }
  public static void main(String args[]) {
    dump(list);
  }
  
  public static void dump(List<String> list) {
    for (String s:list) {
      System.out.println(s);
    }
  }
}

Using the Double Brace Initialization. Careful with this one because it can cause memory leak.

 import java.util.List;
import java.util.ArrayList;
public class InitCollections {
  
  static ArrayList<String> list = new ArrayList<String>() {{
    add("Bart");
    add("Lisa");
    add("Marge");
    add("Barney");
    add("Homer");
    add("Maggie");
  }};

  public static void main(String args[]) {
    dump(list);
  }
  
  public static void dump(List<String> list) {
    for (String s:list) {
      System.out.println(s);
    }
  }
}

Use Arrays.asList()

 import java.util.List;
import java.util.Arrays;
public class InitCollections {

  public static void main(String args[]) {
    List list = Arrays.asList("Bart", "Lisa", "Marge", "Homer", "Maggie");
    dump(list);
  }
  
  public static void dump(List list) {
    for (String s:list) {
      System.out.println(s);
    }
  }
}

Using Static import First a small static class

 package com.rgagnon.howto;

import java.util.Arrays;
import java.util.List;

public class CollectionUtils {
  public static <T> List<T> List(T...elems){
    return Arrays.asList( elems );
  }
}

then

 package com.rgagnon.howto;

import static com.rgagnon.howto.CollectionUtils.List;
import java.util.List;

public class InitCollections {

  public static void main(String args[]) {
    List<String> list = List("Bart", "Lisa", "Marge", "Homer", "Maggie"); 
    dump(list);
  }
  
  public static void dump(List<String> list) {
    for (String s:list) {
      System.out.println(s);
    }
  }
}

Ruby[edit]

array = ["Bart", "Lisa", "Marge", "Homer", "Maggie"]
p array

# In case of string array, it is possible to specify as follows.
array = %w(Bart Lisa Marge Homer Maggie)
p array

Tcl[edit]

set list {Bart Lisa Marge Homer Maggie}
puts $list