An introduction to generics

The syntax for specifying the type of elements in a collection:

CollectionClass<Type> collectionName = new CollectionClass<Type>();

Example 1: A statement that creates an arraylist of type String:

ArrayList<String> codes = new ArrayList<String>();

Example 2: A statement that creates an array list of intergers:

ArrayList<Interger> codes = new ArrayList<Interger>();

Example 3: Code that creates a linked list of type Prouct:

LinkedList<Product> products;
proucts = new LinkedList<Product>();

The syntax for declaring a class that uses generic types:

public class ClassName<TypeVariable [ , TypeVariable ] . . . >{}

Example 4: A class statement for a class that implements a queue

public class GenicrQueue<E>{}

Descriptions:

  • Create typed collections. A typed collection is a collection that can hold only objects of a certain type.
  • To declare a variable that refers to a typed collection, you list the type in angle brackets (<>) follwing the name of the collection class.
  • The type variable can not be a primitive type such as int or double. It can use the wrapper class like Interger, Double and user defined classes.
  • If you do not specify a type for a collection, the collection can hold any type of object.