Friday, November 25, 2011

Best way to declare static map


import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class StaticMapDemo {
      public static final Map<Integer, String> NUMBERS = Collections.unmodifiableMap(getNumbers());
     
      private static Map<Integer, String> getNumbers(){
            Map<Integer,String> map = new HashMap<Integer, String>();
            map.put(1, "one");
            map.put(2, "two");
            map.put(3, "three");
            return map;
      }
     
      public static void main(String[] args) {
            System.out.println(StaticMapDemo.NUMBERS);
      }
}

Output:
{1=one, 2=two, 3=three}

No comments:

Post a Comment