Running the following code in an interactive scala console
val map = new java.util.HashMap[String, Integer]();
map.put("key1", 5)
"Test " + map.get("key1") + " " + map.get() + " " + map.get("key1", "key2") + " " + map.get("key1", "key2", "key3")
returns the following
Test 5 null null null
I would expect this code to result in a compiler error about the wrong number of parameters in the call to the get method in all but the first call. Why is this successfully compiling and just returning null?
Create a HashMap Once we import the package, here is how we can create hashmaps in Java. // hashMap creation with 8 capacity and 0.6 load factor HashMap<K, V> numbers = new HashMap<>(); In the above code, we have created a hashmap named numbers . Here, K represents the key type and V represents the type of values.
HashMap is a data structure that uses a hash function to map identifying values, known as keys, to their associated values. It contains “key-value” pairs and allows retrieving value by key.
Properties Of HashMap In Java : 1) HashMap holds the data in the form of key-value pairs where each key is associated with one value. 2) HashMap doesn't allow duplicate keys. But it can have duplicate values. 3) HashMap can have multiple null values and only one null key.
The Java map is not type safe, in particular the get
method has this signature:
public V get(Object key);
So you can use anything as a key. In Scala you are seeing so-called auto-tupling, something that is deprecated in Scala 2.11, so if you compile your project with -deprecation
, you will see:
[warn] ... Adaptation of argument list by inserting () has been deprecated: leaky (Object-receiving) target makes this especially dangerous.
[warn] signature: HashMap.get(x$1: Any): V
[warn] given arguments: <none>
[warn] after adaptation: HashMap.get((): Unit)
[warn] "Test " + map.get("key1") + " " + map.get() + " " + map.get("key1", "key2") + " " + map.get("key1", "key2", "key3")
[warn] ^
You can turn that into an error with the -Xfuture
compiler flag:
[error] ... Adaptation of argument list by inserting () has been removed.
[error] signature: HashMap.get(x$1: Any): V
[error] given arguments: <none>
[error] "Test " + map.get("key1") + " " + map.get() + " " + map.get("key1", "key2") + " " + map.get("key1", "key2", "key3")
[error] ^
Auto-tupling means map.get()
will be treated as map.get(())
and map.get("key1", "key2")
will be treated as map.get(("key1", "key2"))
.
I recommend using Scala's own collection types unless you have a very particular reason not to do so.
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