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};
Duplicates: HashSet doesn't allow duplicate values. HashMap stores key, value pairs and it does not allow duplicate keys.
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.
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.
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.
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With