## Jupyter at Bryn Mawr College

Public notebooks: /services/public/dblank / CS206 Data Structures / 2017-Spring / Notebooks

# Generics¶

Consider having LinkedLists containing Nodes that held different types of values. We would need:

public class Node {
String data;

Node(String data) {
this.data = data;
}
}

public class Node {
Double data;

Node(Double data) {
this.data = data;
}
}


But you can't do that, because you'd have to give the classes different names to use both.

In any event, Java has a better way, called Generics, and it works like this:

public class Node<T> {
T data;
Node(T data) {
this.data = data;
}
}


It treats a type as if it were a variable. You fill in the variable when you create an instance:

Node<String> snode = new Node<String>("Hello");
Node<Double> dnode = new Node<Double>(34.56);


NOTE: if you use this, you can't assume anything about T. You could though make T implement an interface, though.