Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different Ways of Creating HashMaps

Tags:

java

hashmap

I've been learning about HashMaps recently but I have one question that I can't seem to get a clear answer on. The main difference between -

HashMap hash1 = new HashMap();

vs

HashMap<,>hash1 = new HashMap <,> (); //Filled in with whatever Key and Value you want. 

I thought when you define a HashMap it requires the Key and Value. Any help would be much appreciated. Thank You.

like image 316
StaticGamedude Avatar asked Oct 30 '12 17:10

StaticGamedude


People also ask

What are the HashMap methods available in Java?

Java has a lot of HashMap methods that allow us to work with hashmaps. In this reference page, you will find all the hashmap methods available in Java. For example, if you need to add an element to the hashmap, use the put () method.

How to create a hashmap with integer keys and string values?

You should take a look on Java generics, if you don't specify the types of the HashMap, both key and value will be Object type. So, if you want a HashMap with Integer keys and String values for instance: HashMap<Integer, String> hashMap= new HashMap<Integer, String> ();

How to change elements in a hashmap?

Internally, for every element, a separate hash is generated and the elements are indexed based on this hash to make it more efficient. 2. Changing Elements: After adding the elements if we wish to change the element, it can be done by again adding the element with the put () method.

What is the difference between HashMap and HashSet in Java?

HashMap stores key value pairs (for example records of students as value and roll number as key) and HashSet stores only keys (for example a set if integers). Please refer HashSet in Java for details. Hashmap methods in Java with Examples | Set 2 (keySet (), values (), containsKey ())


2 Answers

Those are the options you have:

J2SE <5.0 style:

 Map map = new HashMap();

J2SE 5.0+ style (use of generics):

 Map<KeyType, ValueType> map = new HashMap<KeyType, ValueType>();

Google Guava style (shorter and more flexible):

 Map<KeyType, ValueType> map = Maps.newHashMap();
like image 122
Andrey Mormysh Avatar answered Sep 23 '22 05:09

Andrey Mormysh


You should take a look on Java generics, if you don't specify the types of the HashMap, both key and value will be Object type.

So, if you want a HashMap with Integer keys and String values for instance:

    HashMap<Integer, String> hashMap= new HashMap<Integer, String>();
like image 38
HericDenis Avatar answered Sep 23 '22 05:09

HericDenis