Dave's Brain

Browse - Programming Tips - How can I initialize a HashMap ?

Date: 2012sep22
Language: Java
Keywords: init

Q.  How can I initialize a HashMap ?

A.  
HashMap<String,String> fruit_to_color = new HashMap<String, String>() {{ put("apple", "red"); put("orange", "orange"); put("banana", "yellow"); }}; // Notice the double brace brackets.
Some people don't like the double brace brackets because it creates an anonymous inner class. But I like it because its compact.

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.