1

I am trying to initialize a Map to zeros in a class. I am doing that in this way:

public class A{   
   private final Map<String,Integer> myMap;

   public A(){

       this.myMap = new HashMap<String,Integer>() {
           {
              put("a",0);
              put("b",0);
            }
       };  
     } 
}

My question: Is this a good implementation? Is there anything wrong with this? Or is there any better way to implement this?

rgettman
  • 176,041
  • 30
  • 275
  • 357
Deeps
  • 327
  • 5
  • 13
  • 1
    how about you `put` a and b it after you initialized it. – Rod_Algonquin Sep 02 '15 at 23:58
  • Agree with @Rod_Algonquin. In your case that's the simplest. – Andreas Sep 03 '15 at 00:00
  • you mean in side the constructor myMap.put("a",0) and myMap("b",0) ? isn't the same? or did I missed something? – Deeps Sep 03 '15 at 00:00
  • If you've declared `final Map` then it means you want/need the varable `myMap` should not be reassigned. If you also need that it should not allow more data add/removal/update, then you should change this design to use an unmodifiable map. – Luiggi Mendoza Sep 03 '15 at 00:02

3 Answers3

2

What Rod_Algonquin meant was:

public class A {
   private final Map<String,Integer> myMap;

   public A() {

      this.myMap = new HashMap<String,Integer>();
      this.myMap.put("a",0);
      this.myMap.put("b",0);
   } 
}

Following up on Luiggi Mendoza's comment, since the Map is declared final, you might have meant for the map to be unmodifiable, but final does not assure that. This will:

public class A {
   private final Map<String,Integer> myMap;

   public A() {
      Map<String,Integer> map = new HashMap<String,Integer>();
      map.put("a",0);
      map.put("b",0);
      this.myMap = Collections.unmodifiableMap(map);
   } 
}
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • Thank you for the answer. @MickMnemonic is also similar to this. – Deeps Sep 03 '15 at 16:56
  • I don't see how this answer addresses the "Is this a good implementation? Is there anything wrong with this?" part of the question. Also, an unmodifiable map that only holds zeros sounds pretty useless; I would assume the OP wants to initialize the map with zeros and later on change some of the values. – Mick Mnemonic Sep 04 '15 at 00:27
2

A better way would be to simply put the values in after you've initialized the map:

myMap = new HashMap<>();
myMap.put("a",0);
myMap.put("b",0);

What your current version is doing is that it's using an instance initializer block (a.k.a. double brace initialization), which creates an unnecessary anonymous class in the background. There is no real benefit in doing so here. On the contrary, it will likely cause a small performance hit.

Community
  • 1
  • 1
Mick Mnemonic
  • 7,808
  • 2
  • 26
  • 30
0

If your real goal is the creation of an immutable Map, I highly recommend using Guava's ImmutableMap.Builder

Brian Kent
  • 3,754
  • 1
  • 26
  • 31