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
  • 51,611
  • 92
  • 240
  • 358

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
  • 12,690
  • 24
  • 87
  • 142
jmj
  • 232,312
  • 42
  • 391
  • 431
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
  • 335,521
  • 76
  • 467
  • 706