The List: 3/27

Welcome to the list. That is, a list is defined in terms of itself. This allows us to define operations in terms of themselves.

Some simple operations:


public class List 
{
    public Object item;
    public List next;
    

    public List() 
    {
	item = null;
	next = null;
    }

    public void add(Object obj) 
    {
	if (next == null) {
	    next = new List();
	    item = obj;
	} else {
	    next.add(obj);
	    
	}
    }

    public Object remove()
    {
	Object o = item;

	if (next != null) {
	    item = next.item;
	    next = next.next;
	}
	return o;
    }


    public boolean isEmpty() 
    {
	return next == null;
    }
    
    
    public int size() 
    {
	if (isEmpty())
	    return 0;
	else return 1 + next.size();
    }
    

    

    public Object get(int i)  
    {
	if (isEmpty()) {
	    throw new IndexOutOfBoundsException();
	}
	
	if (i == 0) {
	    return item;
	} else
	    return next.get(i-1);
    
    }

    static public void main(String args[]) 
    {
	List l = new List();
	l.add("A");
	l.add("B");
	l.add("C");

	System.out.println(l.size());
	System.out.println(l.get(2));
	System.out.println(l.remove());
	System.out.println(l.remove());
	System.out.println(l.remove());
	System.out.println(l.remove());	

    }
}



bershad
Last modified: Fri Feb 27 13:04:59 PST 2004