Skip to content

Generics

Sharina Stubbs edited this page Sep 24, 2019 · 1 revision

Making a class into a generic class that can take different types is not hard. Add in its definition that it can take different types of data. Use angle brackets. Refer to a parameter of whatever type this linked list is of. Type parameter T, once specified can now be used anywhere you want to indicate what the correct type is. Use T for text or E for element. Replace the ints as indicated with T, or E.

public class LinkedList<T> {
    Node<T> head;

    public void insertTail(T value) {
        Node<T> newNode = new Node<>(value); // Java will figure out what needs to be in the empty diamond
        newNode.next = null;
    }

}

Class Node<E> {
    E value;
    Node<E> next;

    Node(E value){

    }
}


// testing must also change
public class LinkedListTest {
    LinkedList<Integer> list;

    @Test
    public void testHead() {
        assertEquals(
            "Head should be 1",
            1,
            list.head.value.intValue()) <--- takes an integer and turn it into an int.
        );
    }
Clone this wiki locally