Для каждого с моим классом не будет работать - PullRequest
0 голосов
/ 01 декабря 2009

Привет всем, я работаю с Java.
Поэтому я пишу класс с именем OrderedSet . Это класс, который пересекается между множеством и очередью. Другими словами, это очередь без дубликатов. Поэтому я знаю, что должен реализовать интерфейс Iterable и написать метод итератора. Чтобы написать метод, я должен реализовать интерфейс Iterator .

package comp345;

import java.util.Iterator;
import java.util.NoSuchElementException;

class OrderedSet implements Iterable<Object> {
    private Object[] queue; // This is how the OrderedSet is represented, a
                            // queue of Objects
    private int counter; // Counter to keep track of current position of queue
    private int queueSize; // Keep track of the queue;

    // Constructor
    public OrderedSet(int size) {
        this.queue = new Object[size];
        this.counter = 0;
        this.queueSize = size - 1;

        // Instantiate each instance of the object in the object array
        for (int i = 0; i < queue.length; i++) {
            queue[i] = new Object();
        }
    }

    /**
     * Ensures that this collection contains the specified element. If it is not
     * already in the collection it is added it to the back of the queue.
     * 
     * @param e
     *            element whose presence in this collection is to be ensured
     * @return true if this collection changed as a result of the call
     * @throws NullPointerException
     *             if the specified element is null
     */
    boolean add(Object i) {
        if (i == queue[counter]) {
            return false;
        } else if (i == null)
            throw new NullPointerException();
        else {
            // Add Object to back of Queue
            queue[counter] = i;
            return true;
        }
    }

    /**
     * Removes all of the elements from this collection. The collection will be
     * empty after this method returns.
     */
    void clear() {
        for (int i = 0; i < queue.length; i++) {
            queue[i] = null;
        }
    }

    /**
     * Returns true if this collection contains no elements.
     * 
     * @return true if this collection contains no elements
     */
    boolean isEmpty() {
        if (queue[0] == null)
            return true;
        else
            return false;
    }

    /**
     * Retrieves, but does not remove, the head of this queue, or returns null
     * if this queue is empty
     * 
     * @return the head of this queue, or null if this queue is empty
     */
    Object peek() {
        if (queue[counter] != null)
            return queue[counter];
        else
            return null;
    }

    /**
     * Retrieves and removes the head of the queue.
     * 
     * @return the head of this queue
     * @throws NoSuchElementException
     *             if this queue is empty
     */
    Object remove() {
        if (queue[0] != null) {
            Object temp = queue[0];

            queue[0] = queue[1];

            return temp;

        } else
            throw new NoSuchElementException();
    }

    public class SetIterator implements Iterator<Object> {
        private int counter;

        public SetIterator() {
            this.counter = 0;
        }

        @Override
        public Object next() {
            counter++;

            if (queueSize == counter)
                return null;

            else if (queue[counter] != null)
                return (Object) queue[counter];

            else
                throw new NoSuchElementException();
        }

        @Override
        public boolean hasNext() {
            counter++;

            if (queueSize < counter)
                return false;
            else if (queue[counter] != null)
                return true;

            return false;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }

    @Override
    public Iterator<Object> iterator() {
        return new SetIterator();
    }

    public static void main(String args[]) {
        OrderedSet os;
        os.add("hello");
        os.add(4);
        os.add("bye");

        for (Object o : os) {
            System.out.println(o);
        }
    }
}

Ответы [ 2 ]

4 голосов
/ 01 декабря 2009

Я вижу как минимум одну проблему.
Присмотритесь к вашему hasNext() методу.

Вы действительно хотите увеличить переменную counter?

2 голосов
/ 01 декабря 2009

Проблема с вашим кодом здесь:

 OrderedSet os;       
 os.add("hello");

Вы объявили ссылку на os, но вы ничего не присвоили. Компилятор не допустит этого. Вы должны сделать:

 OrderedSet os = new OrderedSet(10);

Есть другие проблемы с вашим кодом (@hallidave нашел один), но это первая проблема.

В общем, когда у вас есть проблема с ошибкой, вы должны спрашивать больше информации, чем "она не работает". Точное сообщение об ошибке будет иметь большое значение для ответа на вопрос. Я знаю, что сообщения об ошибках компилятора пока что мало что значат для вас, но когда вы получите больше опыта, они будут.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...