I am writing a generic linked list implementation in Java. The code is
public class LinkedList<T> {
private Node<T> top;
private int no_of_items;
private class Node<T extends Comparable<? super T>> {
T data;
Node<T> next;
}
public LinkedList() {
top = null;
}
public boolean isEmpty() {
return (top == null);
}
public void insert(T item) {
Node<T> node = new Node<T>();
node.data = item;
node.next = top;
if(isEmpty()) {
top = node;
} else {
Node<T> n = top;
while(n.next != null) {
n = n.next;
}
n.next = node;
}
no_of_items++;
}
}
What I want is that T should be Comparable. While compiling this code I am getting an error where I initialize the Node.
Bound Mismatch the type T is not a valid substitute for the bounded parameter <T extends Comparable<? super T>> of the type LinkedList<T>.Node<T>
I am not able to figure out what is the issue here.
I solved the error myself. The correct code would be
The answer lies in that when we use a generic type T in a top class and we have non static inner class, the same T is visible in the inner class as well.
Thanks,