Search code examples
javacollectionsinitialization

Fill hash map during creation


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};

Solution

  • 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.