Java Reference
In-Depth Information
void putAll(Map<? extends K,? extends V> m) : Inserts all mappings contained in the
given map in this map.
V remove(Object key) : Removes a mapping for the given key.
int size() : Returns the number of mappings in this map.
Collection<V> values() : Returns a collection of all values in the map; note that this func-
tion does not return a set (like keyset() does), as duplicate values may exist in the map.
A second point I want to make at this point is related to so‐called “generics” in Java. When glancing
over the code and method lists, you might be wondering what the use of <T> , <? extends T> , and
<String> in ArrayList<String> indicates. Generics was added to Java in 2004, in Java SE 5 to be
precise. Put briefly, generics allow classes and methods to work with objects of various classes, with-
out declaring up front what these classes should be while still retaining compiler safety checks. To
illustrate this, try writing the following in Eclipse:
ArrayList aList = new ArrayList();
aList.add(2);
aList.add("Alice");
This will work, but Eclipse will throw up warnings complaining about the fact that ArrayList should
be parameterized. To explain what this means, try to think about what a list should represent. Basically,
a list class should be able to store a list of objects that all belong to a specific type. Which type? Well,
when rolling the custom SetAsArray before, you enforced all items to be Strings , but ideally, you
would like to keep this generic , as lists, sets, and maps should be able to contain objects of any type. This
is exactly why the example provides this type when instantiating collection types, like so:
ArrayList<String> aList = new ArrayList<String>();
aList.add(2);
aList.add("Alice");
Initializing collections in this way allows the Java compiler to perform an additional number of type
checks. If you're following along, you'll note that Eclipse now displays an error when trying to add
an integer (2) to this list, as the list is only allowed to hold Strings .
Now what if you want your list to hold any kind of object? Then you can just write:
ArrayList<Object> aList = new ArrayList<Object>();
aList.add(2);
aList.add("Alice");
In general, however, it's best to be as precise as possible when instantiating collections (and other
classes using generics). Not only does this allow Java to perform safety checks for you, but another
reason is that Java will use the class you provided when instantiating the collection to return objects
stored in the collection when retrieving them, for instance:
ArrayList<Object> aList = new ArrayList<Object>();
aList.add(new Dog("Puppers")); // Add a Dog object as the first item
aList.add(2);
aList.add("Alice");
Object item = aList.get(0); // Get first item
Search WWH ::




Custom Search