public void printList( ){
Node<E> p ;
System.out.printf( ” [ ” ) ;
for ( p=head.next ; p != null ; p=p.next )
System.out.print( p.element ) ;
System.out.printf( ” ] ” ) ;
}
public void addLast (E e){
Node<E> p = head; // <--- data type Node<E>, var name = p, but what is head type?
while ( p.next != null )
p = p.next ;
p.next = new Node<E>(e , null ) ;
}
Generics Example:
public class Box {
private Object object;
public void set(Object object) { this.object = object; }
public Object get() { return object; }
}
Using Generics:
// T stands for "Type"
public class Box<T> {
private T t;
public void set(T t) {
this.t = t;
}
public T get() {
return t;
}
}
I have a general idea of how linked list work intuitively however I can’t see it in code.
I know you have the element and a reference to the next node. In the code above, how does the “.” operator work as it traverses through the list until null is reached?
I believe ‘next’ is a reference variable. when it does p=p.next, how does it work in code/computer?
On a unrelated note, node ? instead of node(E)? difference? In the example above, it seems ‘object’ was replaced by ‘t’, i can’t see the advantage. ;S
Any help is really appreciated, thanks in advance!
It might help to think of a LinkedList as a List of linked Nodes. Where each Node will hold a reference to the next Node (if one exists). I’m not sure if it will help, but when I had to do this assignment in School I found that looking through the API and trying to use it very helpful.
With Generics Node will be a Node of type Object Where Node will be a Node of a specific type. For example, LinkedList will hold Strings. This, might help to get a better understanding of how generics work.
Here is a simple example of using generics: