Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly use HashMap?

HashMap savedStuff = new HashMap();
savedStuff.put("symbol", this.symbol); //this is a string
savedStuff.put("index", this.index); //this is an int

gives me the warning:

HashMap is a raw type. References to generic type HashMap<K,V> should be parameterized  
like image 450
Sheehan Alam Avatar asked Sep 04 '10 02:09

Sheehan Alam


People also ask

When should a HashMap be used?

Using HashMap makes sense only when unique keys are available for the data we want to store. We should use it when searching for items based on a key and quick access time is an important requirement. We should avoid using HashMap when it is important to maintain the same order of items in a collection.

What is the problem with HashMap?

In HashMap (or HashTable ) you can only have UNIQUE KEYS, you cannot have different values assigned to the same key. In your code you attempt put 2 different values with the same key: map.

What is the disadvantage of using HashMap?

Disadvantages of HashMapPotential of collision when 2 distinct keys generate the same hashCode() value worse the performance of the hashMap. Occasionally HashMaprequires resizing when the original size of HashMap buckets are full.


1 Answers

This is simple code for use of hashmap. There i will use key as integer and value as string type. Map is very useful when our functionality works on key and values pairs. Below is a simple example of use hashmap. I hope it is very useful for all.

public class CreateHashMap {

    public static void main(String[] args) {

    Map<Integer,String> map = new HashMap<Integer,String>();

    /*
     * Associates the specified value with the specified key in 
       this map (optional operation). If the map previously 
       contained a mapping for the key, the old value is 
       replaced by the specified value
     */
        map.put(1,"ankush");
        map.put(2, "amit");
        map.put(3,"shivam");
        map.put(4,"ankit");
        map.put(5, "yogesh");

        //print hashmap
        System.out.println("HashMap = "+map);


    }

}

Reference : create and use of map

like image 158
Anuj Dhiman Avatar answered Sep 24 '22 19:09

Anuj Dhiman