Basic hash maps
Maps in Gosu inherit from the Java class java.util.HashMap.
Creating a hash map
To create an empty map, you use generics notation to specify the type of object that the map
contains. For example, define a HashMap that maps a
String object to another String object:
var emptyMap = new HashMap<String, String>()In many cases, you need to initialize the map with data. Gosu provides a natural syntax for initializing maps similar to initializing arrays and lists.
For example, the following code creates
a new HashMap where "aKey" and "bKey" are keys, whose values
are "aValue" and "bValue" respectively:
var strMap = new HashMap<String, String>(){"aKey" -> "aValue", "bKey" -> "bValue"}That code is shorthand for the following code:
var strs = new HashMap<String, String>()
strs.put("aKey", "aValue")
strs.put("bKey", "bValue")
This Gosu syntax simplifies the declaration of static final data structures of this type, and produces more readable code than the equivalent Java code.
Types of the initialized map
For even more concise code, omit the new expression entirely, including
the type:
var m = {"aKey" -> "aValue", "bKey" -> "bValue"}
Although the type name is omitted, the map is not
untyped. Gosu infers that you want to create a HashMap by the way you use the
hyphen and greater than symbol. Gosu infers the exact type of the map
from the object types that you pass to the initialization.
The run-time type is always:
java.util.HashMap<java.lang.Object, java.lang.Object>The compile-time
type depends on the types of what you pass as keys and values. Gosu infers
the type of the map to be the least upper bound of the components of the map. If you are
consistent in the type of your keys and the types of your values, the
compile-time type of the map is HashMap<KEY_TYPE, VALUE_TYPE>.
If you pass different types
of objects to either the keys or the values, Gosu finds the most specific
type that includes all of the items that you pass. Gosu finds a common
ancestor class that all the objects support. If the types implement interfaces,
Gosu attempts to preserve commonality of interface support in the map
type. This behavior ensures that your map and its elements act as expected
with APIs that rely on support for interfaces. In some cases, the resulting
type at compile time is a compound type. A compound type, which combines zero or one classes
and one or more interfaces into a single type. The purpose is for you
to be able to use that list and its elements with APIs that require the
interface as the argument type. At run-time, the type of the initialized
map is HashMap<Object, Object>.
See also
