-
List problems
I am right now reading a Java course. And I have totally get stucked with one of my task.
My task is that I am trying to make a list that i can add and get object from.
I have an API I build my list from, so the methods and the constructor in my classes have to be there. The problem come when I am trying to add some objects to the list. When I am trying to add an object, I only get back null object. And I have no ideé what the problem is. I would be really happy if someone please could told me what I am doing wrong.
Code:
import java.lang.Object.*;
public class Node {
Object item;
Node next;
public Node (java.lang.Object newItem)
{
setItem(newItem);
setNext(null);
}
public Node(java.lang.Object newItem, Node nextNode)
{
setItem(newItem);
setNext(nextNode);
}
public void setItem (java.lang.Object newItem)
{
item = newItem;
}
public java.lang.Object getItem()
{
return item;
}
public void setNext(Node nextNode)
{
next = nextNode;
}
public Node getNext()
{
return next;
}
}
Code:
import java.lang.Object.*;
public class ListReferencedBased implements ListInterface{
int numItems;
Node head;
private Node find (int index)
{
Node current = head;
if (index >= numItems)
{
return null;
}
else
{
for (int count=0; count<index; count++)
{
current = current.getNext();
}
return current;
}
}
public ListReferencedBased()
{
head = null;
numItems = 0;
}
@Override
public void add(int index, Object item) throws ListIndexOutOfBoundsException {
Node pre, cur;
if (index < 1 || index > numItems+1)
{
numItems++;
}
if (isEmpty()) {
head = new Node(item);
numItems++;
}
else{
head = new Node(find(index), head);
numItems++;
}
/* pre = find(index-1);
cur = pre.getNext();
pre.setNext(new Node(item, cur));
*/
}
@Override
public Object get(int index) throws ListIndexOutOfBoundsException {
head.setNext(find(index));
if(find(index) != null)
{
return head.getItem();
}else{
return null;
}
}
@Override
public boolean isEmpty() {
if(numItems == 0)
{
return true;
}
else
{
return false;
}
}
@Override
public void remove(int index) throws ListIndexOutOfBoundsException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void removeAll() {
head.next = null;
}
@Override
public int size() {
/* numItems=0;
while(head!=null)
{
numItems++;
head.getNext();
}*/
return numItems;
}
}