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'?
A HashMap stores key-value mappings. In this tutorial, we'll discuss how to store values of different types in a HashMap.
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.
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.
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.
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 <>.
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.
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