Associative array/Merging: Difference between revisions
→{{header|Java}}
m (BaCon moved to the BASIC section.) |
|||
Line 771:
=={{header|Java}}==
<p>
<syntaxhighlight lang="java">import java.util.*;▼
See also, [https://rosettacode.org/wiki/Associative_array/Creation#Java Java - Associative array/Creation].
</p>
<p>
This task illustrates the difference between statically typed languages, and dynamically typed.<br />
With exception to the <code>var</code> keyword, Java is statically typed.
So, using an undefined, non-static, <kbd>value</kbd>, creates a trivial situation.
</p>
<p>
A good way to understand this task is that it's not possible in a static-typed language.<br />
It defeats the purpose of defining the data-type.<br />
For Java, if you're going to use <code>Object</code> as your data-type, you need to re-evaluate the method of abstraction.
</p>
<p>
Java offers <kbd>generics</kbd>, <kbd>interfaces</kbd>, and <kbd>abstract classes</kbd> for this task.
</p>
<p>
Considering this, to complete this specific task, I would just store the values as <kbd>strings</kbd>.
</p>
import java.util.LinkedHashMap;
import java.util.Map;
<syntaxhighlight lang="java">
mapA.put("name", "Rocket Skates");
▲ Map<String, Object> base = new HashMap<>();
▲ base.put("price", 12.75);
▲ base.put("color", "yellow");
▲ Map<String, Object> update = new HashMap<>();
▲ update.put("price", 15.25);
▲ update.put("color", "red");
update.put("year", 1974);▼
mapC.putAll(mapB);
</syntaxhighlight>
To show that the original <kbd>map</kbd>s are not affected.
<syntaxhighlight lang="java">
for(Map.Entry<String, String> entry : mapA.entrySet())
System.out.printf("%-20s%s%n", entry.getKey(), entry.getValue());
for(Map.Entry<String, String> entry : mapB.entrySet())
System.out.printf("%-20s%s%n", entry.getKey(), entry.getValue());
▲}</syntaxhighlight>
for(Map.Entry<String, String> entry : mapC.entrySet())
System.out.printf("%-20s%s%n", entry.getKey(), entry.getValue());
</syntaxhighlight>
<pre>
name Rocket Skates
price 12.75
color yellow
</pre>
<pre>
price 15.25
color red
year 1974
</pre>
<pre>
name Rocket Skates
price 15.25
color red
year 1974
</pre>
<p>
While not recommended, due to scalability, if you did want to use an <code>Object</code> as the value, you could use the following implementation.<br />
This will produce the same output as above.
</p>
<syntaxhighlight lang="java">
Map<String, Object> mapA = new LinkedHashMap<>();
mapA.put("name", "Rocket Skates");
mapA.put("price", 12.75);
mapA.put("color", "yellow");
Map<String, Object> mapB = new LinkedHashMap<>();
mapB.put("price", 15.25);
mapB.put("color", "red");
Map<String, Object> mapC = new LinkedHashMap<>();
mapC.putAll(mapA);
mapC.putAll(mapB);
</syntaxhighlight>
=={{header|JavaScript}}==
|