Path: csiph.com!x330-a1.tempe.blueboxinc.net!newsfeed.hal-mli.net!feeder1.hal-mli.net!border3.nntp.dca.giganews.com!Xl.tags.giganews.com!border1.nntp.dca.giganews.com!nntp.giganews.com!local2.nntp.dca.giganews.com!nntp.earthlink.com!news.earthlink.com.POSTED!not-for-mail NNTP-Posting-Date: Sun, 16 Oct 2011 19:02:43 -0500 Date: Mon, 17 Oct 2011 01:02:44 +0100 From: Patricia Shanahan User-Agent: Thunderbird 1.5.0.2 (Windows/20060308) MIME-Version: 1.0 Newsgroups: comp.lang.java.programmer Subject: Re: constructing a constant HashMap References: <49CdnacDvODl-wfTnZ2dnUVZ_hmdnZ2d@earthlink.com> In-Reply-To: Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Message-ID: Lines: 31 X-Usenet-Provider: http://www.giganews.com NNTP-Posting-Host: 83.244.254.163 X-Trace: sv3-6hrvWCbNY6eTXlU8d5f7up4hWHc4ZIhyTFvwH3iiwBefWvFNr7CbbTTHDQkBWgaY9QVI0a9XD8fzH2g!UWUmgiTNyqnZFmadjSq4CX+JGsm0VVn6L+B9uRLjmBY4G2V2DTrv4XlAMyYXAJtX+Gpb8h+dq/cA!NP8c9hkRRAdp7+v5hCt72DXFB6PzexDj47EsvAtV7A00UUY= X-Abuse-and-DMCA-Info: Please be sure to forward a copy of ALL headers X-Abuse-and-DMCA-Info: Otherwise we will be unable to process your complaint properly X-Postfilter: 1.3.40 X-Original-Bytes: 2247 Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:8882 Tom Anderson wrote: > On Sun, 16 Oct 2011, B1ll Gat3s wrote: > >> On 16/10/2011 1:07 AM, Patricia Shanahan wrote: >>> Roedy Green wrote: >>>> What is your preferred way of building a HashMap when all the values >>>> are known at compile time? >>> >>> If the map is a field, I often use an instance or static initializer >>> immediately after the map's declaration: >>> >>> Map myMap = new HashMap(); >>> { >>> myMap.put("aaa", "bbb"); >>> ... >>> } > > For static final variables (suggested by "all the values are known at > compile time"), i would suggest a slight variation: > > static final Map myMap; > static { > Map tmpMap = new HashMap(); > tmpMap.put("aaa", "bbb"); > myMap = Collections.unmodifiableMap(tmpMap); > } Yes, that is indeed an improvement, given the lack of intent to modify the map after its creation. Patricia