Initialize a Collection

From CodeCodex

Revision as of 15:56, 17 August 2009 by Techmind (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Implementations

Java

The regular way <highlightsyntax language="java122">

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);
   }
 }

} </highlightsyntax> Using a static initializer <highlightsyntax language="java122">

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);
   }
 }

} </highlightsyntax> Using the Double Brace Initialization. Careful with this one because it can cause memory leak. <highlightsyntax language="java122">

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);
   }
 }

} </highlightsyntax> Use Arrays.asList() <highlightsyntax language="java122">

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);
   }
 }

} </highlightsyntax> Using Static import First a small static class <highlightsyntax language="java122">

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 );
 }

} </highlightsyntax> then <highlightsyntax language="java122">

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);
   }
 }

} </highlightsyntax>