program compilation problem
public class SingleLinkedListTest {
SingleLinkedList<String> names = new SingleLinkedList<String>();
names.addFirst("Sam");
}
public class SingleLinkedList<E>{
private Node<E> head;
private int size;
//add element at first node of the list
public void addFirst(E dataItem){
head = new Node<E>(dataItem, head);
size++;
}
// adds element after the specified node of the list
private void addAfter(Node<E> node, E dataItem){
node.next = new Node<E>(dataItem, node.next);
size++;
}
// removes the first node from the list
@SuppressWarnings("unused")
private E removeFirst(){
Node<E> temp = head;
if (temp != null)
head = head.next;
if (head!= null){
size--;
return temp.data;
}
else
return null;
}
//removes an element after a specified node of the list
@SuppressWarnings("unused")
private E removeAfter(Node<E> node){
Node<E> temp = node.next;
if (temp != null){
node.next = temp.next;
size--;
return temp.data;
}
else
return null;
}
// gets a string representation of the elements present in a list
public String toString(){
@SuppressWarnings("unchecked")
Node<String> nodeRef = (Node<String>) head;
String result = "";
while(nodeRef != null){
result.concat(nodeRef.data);
if (nodeRef.next != null)
result.concat("==>>");
nodeRef = nodeRef.next;
}
return result;
}
private Node<E> getNode(int index){
Node<E> node = head;
for(int i= 0; i < index && node != null; i++){
node = node.next;
}
return node;
}
// gets an element at the specified index
public E get (int index){
if(index < 0 || index >= size )
throw new IndexOutOfBoundsException(Integer.toString(index)) ;
Node<E> node = getNode(index);
return node.data;
}
// sets an element at the specified index
public E set(int index, E dataItem){
if (index < 0 || index >= size )
throw new IndexOutOfBoundsException(Integer.toString(index)) ;
Node<E> node = getNode(index);
E result = node.data;
node.data = dataItem;
return result;
}
// adds an element at the specified index
public void add(int index, E dataItem){
if (index < 0 || index > size)
throw new IndexOutOfBoundsException(Integer.toString(index)) ;
if (index== 0){
addFirst(dataItem);
}
else
{
Node<E> node = getNode(index-1);
addAfter(node,dataItem);
}
}
// adds an element at the end of the list
public boolean add(E dataItem){
add(size,dataItem);
return true;
}
private static class Node<E>{
private E data;
private Node<E> next;
private Node(E dataItem){
data = dataItem;
next = null;
}
private Node(E dataItem, Node<E> nodeRef){
data = dataItem;
next = nodeRef;
}
}
}
Re: program compilation problem
What are we supposed to do now? Guess the syntax error? What do we win?
Jos
ps. I moved this thread to the New To Java section; there is nothing advanced about it.