Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting element into HashMap with Map interface

I'm trying Kotlin and I've encountered a small problem that I can't resolve. When I have the following construction I can put elements into the map:

val map = HashMap<String, String>()
map["asd"] = "s"
map.put("34", "354")

However when I create a map with the Map interface I can only read them, what I'm doing wrong ?

val map: Map<String, String> = HashMap<String, String>();
map.put("24", "34") //error
map["23"] = "23" //error

Or maybe I'm confusing something about interfaces in Kotlin ?

like image 750
ashur Avatar asked Jul 16 '15 08:07

ashur


People also ask

How do you add an element to a HashMap?

put() method of HashMap is used to insert a mapping into a map. This means we can insert a specific key and the value it is mapping to into a particular map. If an existing key is passed then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole.

Can you cast Map to HashMap?

In general, you cannot typecast a Map to a HashMap without risk of a class-cast exception. If the Map is a TreeMap then the cast will (and must) fail. You can avoid the exception by making using instanceof to check the type before you cast, but if the test says "not a HashMap" you are stuck.

How do you add entries to a Map?

The standard solution to add values to a map is using the put() method, which associates the specified value with the specified key in the map. Note that if the map already contains a mapping corresponding to the specified key, the old value will be replaced by the specified value.

How do I add a value to a map key?

Use the set() method to add a key/value pair to a Map , e.g. map. set('myKey', 'myValue') . The set() method adds or updates the element with the provided key and value and returns the Map object.


1 Answers

In the first example map gets the type of HashMap, in the second example you cast it to the Interface Map.

Map is a readonly map, there is no put/set, see here

In order to be able to edit the map, you should use MutableMap

like image 113
D3xter Avatar answered Nov 01 '22 08:11

D3xter