ArrayList<Integer> data = new ArrayList<String>();
No, the type of object constructed by new
is not the type of the variable data
.
You can create a generic class.
Pick a name for a the class and a name for the type variable (usually a single capital letter).
Put the type variable inside angle brackets <>
after the class name.
In the code for the class use the type variable instead of a specific type.
Here is the non-generic Node
class from the previous chapters:
public class Node { private int value; private Node next; // Constructor public Node ( int val ) { value = val; next = null; } public int getValue() { return value; } public Node getNext() { return next; } public void setValue( int val ) { value = val; } public void setNext( Node nxt ) { next = nxt; } public String toString() { return "" + value ; } }
The original Node
is not generic.
It can only contain a primitive int
value.
Here is a generic Node
that can hold
a reference to an object of a specified type.
public class GenericNode<E> { private E value; private GenericNode<E> next; // Constructor public GenericNode( E val ) { value = val; next = null; } public E getValue() { return value; } public GenericNode<E> getNext() { return next; } public void setValue( E val ) { value = val; } public void setNext ( GenericNode<E> nxt ) { next = nxt; } public String toString() { return "" + value; } }
The type variable E
says where the particular type you specify in a constructor should go.
E
acts as a placeholder for an actual data type specified when the generic class is used.
Inspect the following use of a constructor:
GenericNode<String> names = new GenericNode<>();
This in effect replaces the type variable E
with the class name String
.
The type variable can be any identifier. But it is conventional to use single capital letters, often "E" for Element. This visually separates type variables from other variables and makes programs more understandable.
Could the type specified for E
be a class you designed,
like the class CheckingAccount
from a previous chapter?