I'm creating a program which has data in the linklist. I'm trying to print out the element in the linklist from head to tail and tail to end, but for some reason, I run into some compiler error. I don't know why it won't let me call the hasPrevious and previous method in my lterator.

This is the class that contain all the method I'm going to used:

/**
 * Linked implementation of the <code>java.util.List</code> interface
 * by extending <code>java.util.AbstractSequentialList</code>.<p>
 */


import java.util.*;
import java.io.Serializable;
import java.util.AbstractList;

public class LinkedList<E> extends AbstractSequentialList<E> implements Serializable
{

    private transient int size = 0;   // size can never be < 0
    private transient DLNode<E> head;
    private transient DLNode<E> tail;

    public LinkedList() 
    {
      size = 0;
      tail = new DLNode<E>();		         // the tail dummy node
      head = new DLNode<E>( null, null, tail );  // the head dummy node
      tail.setPredecessor( head );
      modCount = 0;
    }

     public void add(int index, E o) 
     {
        ListIterator<E> iter = this.listIterator( index );
        iter.add( o );
     }

    public ListIterator<E> listIterator( int index ) 
    {
        if (( index < 0 ) || ( index > size ) )
            throw new IndexOutOfBoundsException("index " + index
                             + " is out of range: 0 to " + size);
        return new LinkedListIterator<E>( index );
    }

    public int size()
    {
        return this.size;
    }


    private DLNode<E> getNodeAt( int index ) 
    {
        // check for empty list and appending at the tail
        if ( index == this.size ) return tail;
        DLNode<E> p = null;

        if ( ( index < this.size / 2 )  ) 
        { // start at beginning of the list
            p = head.getSuccessor();
            for ( int i = 0; i != index; i++ )
              p = p.getSuccessor();
        }
        else {
            p = tail.getPredecessor();
            for ( int i = this.size - 1; i != index; i-- )
              p = p.getPredecessor();
        }
        return p;
    }


    public class LinkedListIterator<E> implements ListIterator<E> 
    {
        // invariant: cursor should always reference a node from
        //  head's successor to tail. cursor should never reference head.
        private DLNode<E> cursor;  // references node to be returned by next(), which
                                // is successor to node to be returned by previous()

        private DLNode<E> lastNodeReturned;  // last node reterned by next() or previous()
        private int nextIndex; // index of node returned by NEXT call to next()

        /**
         * Provides fail-fast operation of the iterator. For each call to an
         * iterator method, expectedModCount should be equal to the collection's
         * modCount, otherwise an intervening change (concurrent modification)
         * to the collection has been made and we cannot guarantee that the
         * iterator will behave correctly.
         */
        private int expectedModCount;

        /**
         * the contract of remove() says that each call to remove() must have
         * been preceded by a call to next()/previous() (they are paired). So if there has
         * been NO call to next()/previous() prior to a remove() or if there were two
         * remove() calls without an intervening next()/previous() call, it is NOT ok to
         * try to remove an item.
         */
        private boolean okToRemove;

        // pre: 0 <= index <= size()
        public LinkedListIterator( int index ) 
        {
            if (( index < 0 ) || ( index > size ) )
                throw new IndexOutOfBoundsException("index " + index
                             + " is out of range: 0 to " + size);
            // cursor starts out at the target node's predecessor
            //DLNode temp = head;
            if ( index == 0 )
              cursor = (DLNode<E>)head.getSuccessor();
            else if ( index == size )
                cursor = (DLNode<E>)tail;
            else
                cursor = (DLNode<E>)getNodeAt( index );
            nextIndex = index;
            okToRemove = false;
            expectedModCount = modCount;
            lastNodeReturned = null;
        }

        public E next() 
        {
            if ( ! hasNext() )
                throw new NoSuchElementException( "no next element" );

            checkForConcurrentModification();

            okToRemove = true;

            // next() is the inverse of previous():
            //   always get the element field THEN advance the cursor
            nextIndex++;
            E element = cursor.getElement();
            lastNodeReturned = cursor;
            cursor = cursor.getSuccessor();
            return element;
        }

        public E previous() 
        {
            checkForConcurrentModification();
            if ( ! hasPrevious() )
                throw new NoSuchElementException( "no previous element" );

            okToRemove = true;

            // previous() is the inverse of next():
            //   always decrement the cursor THEN get the element field
            nextIndex--;
            cursor = cursor.getPredecessor();
            lastNodeReturned = cursor;
            //System.err.println("previous(): cursor is " + cursor);
            return cursor.getElement();
        }

        // nextIndex is the index of the element to be returned by next(),
        //  so the previous index will be one less than nextIndex
        public int previousIndex() 
        {
            checkForConcurrentModification();
            if ( hasPrevious() ) return nextIndex - 1;
            else return -1;
        }

        public int nextIndex() 
        {
            checkForConcurrentModification();
            if ( hasNext() ) return nextIndex;
            else return size;
        }

        public boolean hasNext() 
        {
            checkForConcurrentModification();
            return cursor != tail;
        }

        public boolean hasPrevious() 
        {
            checkForConcurrentModification();
            return cursor.getPredecessor() != head;
        }

        public void add( E o ) 
        {
            checkForConcurrentModification();

            okToRemove = false;

            DLNode<E> newnode = new DLNode<E>( o, cursor.getPredecessor(), cursor );
            newnode.getPredecessor().setSuccessor( newnode );
            cursor.setPredecessor( newnode );

            nextIndex++;
            size++;       // update List data field
            modCount++;   // update List data field
            expectedModCount = modCount;
        }

        public void remove() 
        {
            checkForConcurrentModification();

            // check that there has been a next()/previous() message to provide
            // an element to remove
            if ( !okToRemove )
                throw new IllegalStateException();

            okToRemove = false;

            // either the cursor or nextIndex needs to be updated
            if ( cursor == lastNodeReturned )  // removing item returned by a previous() call
                cursor = cursor.getSuccessor();     // move cursor forward
            else                               // removing item returned by a next() call
                nextIndex--;                   // move nextIndex backward

            lastNodeReturned.getPredecessor().setSuccessor( lastNodeReturned.getSuccessor() );
            lastNodeReturned.getSuccessor().setPredecessor( lastNodeReturned.getPredecessor() );

            // now do cleanup
            lastNodeReturned.setSuccessor( null );
            lastNodeReturned.setPredecessor( null );
            lastNodeReturned.setElement( null );
            lastNodeReturned = null;

            size--;       // update LinkedList data field
            modCount++;   // update AbstractList data field
            expectedModCount = modCount;
        }

        // change the value stored by the last node returned by next() or
        //   previous()
        public void set( E o ) 
        {
            checkForConcurrentModification();
            lastNodeReturned.setElement( o );
        }

        private void checkForConcurrentModification() 
        {
            if ( expectedModCount != modCount )
                throw new java.util.ConcurrentModificationException();
        }

    }

}

This is my main class. I already have five things in the linklist. I got no problem printing from head to tail. But I'm running to the problem that print from tail to head. This is how I print it.

Iterator iter1 = l1.iterator();
		
		while(iter1.hasPrevious())
		{
			System.out.println(iter1.previous());
		}

The compiler error is the previous is undefined in Iterator which I don't get why because I create the method already. Where did I do wrong?

some compiler error.

Can you copy and paste here the full text of the error messages?
It has important information about your problem.

Have you read the API doc for the Java SE class Iterator? The compiler doesn't think the class has the method you are trying to use.

Never mind, I my syntax wrong after I check the APT. Thank you so much for the reminder. But I have another problem with reading a file from disk.

This is how I write my writing to disk method:

try
		{
			ObjectOutputStream input = new ObjectOutputStream(new FileOutputStream("AccountRecord.ser"));
			input.writeObject(l1); 
			input.close();
			
		}
		catch (IOException ioException) {
			System.err.println("Error opening file.");
		}

This is how I write my reading and printing:

try
		{
			ObjectInputStream output = new ObjectInputStream(new FileInputStream("AccountRecord.ser"));
			LinkedList<AccountRecordSerializable> list = (LinkedList<AccountRecordSerializable>)output.readObject();
			
			System.out.println(list);
			
			
		}
		catch(Exception ex)
		{
			System.out.printf("Error opening file.");
		}

It does not give me compiler error or anything. It would just printout the message that "Error opening file" when I try to read and print from the disk. Where did I do wrong?

Exception ex contains full details of what went wrong and exactly where it went wrong. Don't ignore it. Use ex.printStackTrace(); to see what it can tell you.

Yes, please do that. You may be going wrong during the printing part. If AccountRecord.ser is to be created while writing, as it seems from your code, you will have to define the file first, and then use the <newly_created_file's_object>.createFile() method and only then write to it. Hope this helps! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.