Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill hash map during creation [duplicate]

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}; 
like image 352
Damir Avatar asked Jan 27 '11 09:01

Damir


People also ask

Does hash map allow duplicate values?

Duplicates: HashSet doesn't allow duplicate values. HashMap stores key, value pairs and it does not allow duplicate keys.

How do you prevent duplicates in maps?

If you have to avoid duplicates you also know we have to use Set from the collections. You can do like Map<set<id>,sObject> newMap = Map<set<id>,sObject>(); Please take it as a general solution which you can modify as per your requirement.

What happens if we enter duplicate key in map?

If you try to insert the duplicate key, it will replace the element of the corresponding key. HashMap is similar to HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values.

How do you populate a hash map?

To populate HashMap in previous Java versions, we have to use the put() method. You can also make a map immutable once you populate the static HashMap. If we try to modify the immutable Map, we will get java. lang.


Video Answer


2 Answers

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.

like image 69
jmj Avatar answered Oct 06 '22 01:10

jmj


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

like image 31
Michael Borgwardt Avatar answered Oct 06 '22 03:10

Michael Borgwardt