Behaviour of Generic Type in Java

Stack class

public class Stack
{
public void push(LinkedList ll) {

}

LinkedList class

class LinkedList<Item>
{
 private class Node<Element>
 {
    private Element value ;
    private Node<Element> next;
 }
 Node(Element value, Node<Element> ref) {
        this.value = value;
        this.next = ref;
    }
}

I have my main method in class Stack , in it I have made an object of class Stack and and object of class LinkedList and I am calling push method. What I dont understand is that If I use (LinkedList<Type> ll) as argument compiler is showing an error:

cannot find symbol
    public void push(LinkedList<Item> ll) {
                                ^
  symbol:   class Item
  location: class Stack

Why is this error occuring ang why it works fine if i use

public void push(LinkedList ll) 

Thanks in advance

Jon Skeet
people
quotationmark

In the declaration of LinkedList, Item is the name of a type parameter. It only has direct meaning within the LinkedList class itself.

When you're declaring your push method and using LinkedList, you'd specify a type argument, i.e. the element type of the linked list. For example, this would be fine:

public void push(LinkedList<String> ll)

... but Item isn't a meaningful identifier.

Now as an alternative, you could make your Stack class generic too:

public class Stack<Item>
{
    public void push(LinkedList<Item> ll) { ... }    
}

... but you should be aware that the fact that both the LinkedList and Stack declarations use a type parameter called Item is effectively a coincidence. It would be exactly equivalent to write:

public class Stack<T>
{
    public void push(LinkedList<T> ll) { ... }    
}

people

See more on this question at Stackoverflow