Generics

From Informatics

Jump to: navigation, search

Generics were developed to handle type safety of collections. For instance, a declaration like:

Set addresses = new HashSet();

would essentially have to trust users to added only Address objects to this Set. If you did not trust them, you would have to check every member of the collection at runtime ... this is expensive (Complexity O(n)).

The idea with generics is to prevent users from inputting invalid values into the collection at compile time.

With generics, the above would look like:

Set<Address> addresses = new HashSet<Address>();

Trying to do something like:

addresses.add(new Integer(5)); will cause a compiler error.

A Declaration like this:

public class ListManager<Type extends List<? extends Number>>{

...

}

This reads "ListManager can be parameterized with a type that extends List, and the List can only contain the object Number or the subclasses of Number."

Personal tools