views:

28

answers:

1

I'm writing a deque implementation with ArrayList as required by my instructor. So far the body of the class looks like this

try {
        while (!endOfFile) {
            character = inputFile.readChar();
            while (!character.equals('\u0003')) {
                if (character.equals('\u0008'))
                    deck.removeBack();
                else
                    deck.addToBack(character);
            }
        }

        while (!deck.isEmpty()) {
            character = deck.removeFront();
            if (character.equals('\u0003'))
                System.out.print("\n");
            else
                System.out.print(character);
        }
    } catch (EOFException e) {
        endOfFile = true;
    }

The deque is initialized as

 Deque<Character> = new deck Deque<Character>()

I've tested my Deque with a separate test class and I'm quite sure that it's working properly. But every time I try to run this read class, it causes a java.lang.OutOfMemoryError at the deck.addToBack(character) line. What is causing the problem and how can it be avoided?

Edit: My implementation of the Deque. The interface was provided by my instructor.

import java.util.*;
public class Deque<T> extends ArrayList<T> implements DequeInterface<T> {

public Deque()
{
   super();
}

public void addToFront(T newEntry) {
    add(0, newEntry);
}

public void addToBack(T newEntry) {
    add(newEntry);
}

public T removeFront() {
    T entry = null;
    entry = get(0);
    remove(0);
    return entry;
}

public T removeBack() {
    T entry = null;
    entry = get(size() - 1);
    remove(size() - 1);
    return entry;
}

public T getFront() {
    T entry = get(0);
    return entry;
}

public T getBack() {
    T entry = get(size() - 1);
    return entry;
}

public boolean isEmpty() {
    if (size() == 0)
        return true;
    else
        return false;
}

public void clear() {
    clear();
}

}

+1  A: 
    while (!endOfFile) {
        character = inputFile.readChar();
        while (!character.equals('\u0003')) {
            if (character.equals('\u0008'))
                deck.removeBack();
            else
                deck.addToBack(character);
        }
    }

Check your outer loop exit conditions.

Does readChar return -1 to indicate end of data? This would likely cause an infinite loop resulting in memory exhaustion.

McDowell
Does it indicate end of data normally? How would I prevent it?
Francis
@Francis - it isn't possible to say without knowing the type of `inputFile`. Check its documentation: http://download.oracle.com/javase/6/docs/api/ But my main point is that if nothing within the loop changes `endOfFile`, the loop will never exit.
McDowell