26

Possible Duplicate:
How to Initialise a static Map in Java

How to fill HashMap in Java at initialization time, is possible something like this ?

public static Map<byte,int> sizeNeeded=new HashMap<byte,int>(){1,1};
Community
  • 1
  • 1
Damir
  • 54,277
  • 94
  • 246
  • 365

2 Answers2

60

byte, int are primitive, collection works on object. You need something like this:

public static Map<Byte, Integer> sizeNeeded = new HashMap<Byte, Integer>() {{
    put(new Byte("1"), 1);
    put(new Byte("2"), 2);
}};

This will create a new map and using initializer block it will call put method to fill data.

Mike
  • 14,010
  • 29
  • 101
  • 161
jmj
  • 237,923
  • 42
  • 401
  • 438
2

First of all, you can't have primitives as generic type parameters in Java, so Map<byte,int> is impossible, it'll have to be Map<Byte,Integer>.

Second, no, there are no collection literals in Java right now, though they're being considered as a new feature in Project Coin. Unfortunately, they were dropped from Java 7 and you'll have to wait until Java 8...

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720