Initializing dictionaries
Dictionaries are so commonplace that it's no wonder that each of the languages we are examining supports them with concrete implementations. Here are some examples of initializing a dictionary, adding a few key/value pairs to the collection, and then removing one of those pairs from the collection.
C#
C# provides a concrete implementation of the dictionary data structure through the Dictionary<TKey, TValue>
class. Since this class is generic, the caller may define the types used for both the keys and values. Here is an example:
Dictionary<string, int> dict = new Dictionary<string, int>();
This example initializes a new dictionary where the keys will be string
types, and the values will be int
types:
dict.Add("green", 1); dict.Add("yellow", 2); dict.Add("red", 3); dict.Add("blue", 4); dict.Remove("blue"); Console.WriteLine("{0}", dict["red"]); // Output: 3Java
Java...