Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java HashMap with or without type?

Tags:

java

hashmap

Should the declaration of a HashMap always include the type e.g.

private HashMap<String, String> test = new HashMap<String, String>();

because I see lots of examples in books where <String, String> is left out so we just have something like:

private Map test= new HashMap();

Which one is 'correct'?

like image 714
Gurt Avatar asked May 14 '11 04:05

Gurt


People also ask

Can HashMap store different data types?

A HashMap stores key-value mappings. In this tutorial, we'll discuss how to store values of different types in a HashMap.

Is HashMap a data type?

The HashMap class of the Java collections framework provides the functionality of the hash table data structure. It stores elements in key/value pairs. Here, keys are unique identifiers used to associate each value on a map. The HashMap class implements the Map interface.

What is Map <> in Java?

A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. It models the mathematical function abstraction.

What is the difference between a HashMap and a HashSet?

HashMap Stores elements in form of key-value pair i.e each element has its corresponding key which is required for its retrieval during iteration. HashSet stores only objects no such key value pairs maintained. Put method of hash map is used to add element in hashmap.


2 Answers

It should really look like

private Map<String, String> test = new HashMap<>();

So elements of both are correct.;) Map is the interface, which defines behavior, and HashMap is an implementation that provides the behavior.

If you want stronger type safety, you should use the generic arguments. While they are not strictly necessary, they add a lot of value at reducing application errors. Since generics were introduced in Java 5, examples from before then won't have show the generic arguments.

The "diamond operator" <> was introduced with Java 7 - it means you can reduce the second occurrence of the generic type specifier to just <>.

like image 101
hvgotcodes Avatar answered Oct 12 '22 00:10

hvgotcodes


Since Java 5, the best option has been to use generics with the <> brackets. This lets you know what types the Map uses for key and value, and performs some compile-time checks to prevent you from adding the incorrect types. It also makes it so you don't have to cast values to the correct type when you get them from the map.

If you want to allow all classes for key and value, you can use the <?, ?> generic declaration. But it's almost always best to be as specific as necessary on your generic types.

Also, it is possible to circumvent the generic checks, but they're definitely better than nothing.

like image 38
Kaleb Brasee Avatar answered Oct 11 '22 23:10

Kaleb Brasee