LinkedOrderedList和LinkedList实现

时间:2016-03-19 23:20:14

标签: java linked-list

所以我应该创建一个创建动物列表的程序。程序按名称对它们进行排序,并按字母顺序将它们放入列表中。但每次我点击“显示动物”按钮它都没有显示任何内容,我发现这是list.size()的问题,所以我将其更改为整数10来测试它,它显示但它只显示第一个动物补充说。我不确定问题出在哪里,我真的很困惑,这是我的代码:

这是LinkeList类

package animal;
import exceptions.ElementNotFoundException;
import exceptions.EmptyCollectionException;
import java.util.*;

/**
 * @author Sharon Umute 
 * Comp 139 001B
 * @param <T>
 */
public class LinkedList<T> implements ListADT<T> {

protected int count;
protected SinglyLinkedNode head, tail;
protected int modCount;

/**
 * The LinkedList constructor creates an empty list
*/
public LinkedList(){
    count=0;
    head=tail=null;
    modCount = 0;
}
/**  
 * Removes and returns the head element from this list. 
 * 
 * @return the head element from this list
 */
@Override
public T removeFirst() throws EmptyCollectionException {
    if(isEmpty()){
        throw new EmptyCollectionException("list");
    }

    T result=(T) head.getElement();
    head=head.getNext();
    count--;
    modCount++;
    return result;
}

/**  
 * Removes and returns the tail element from this list. 
 *
 * @return the tail element from this list
 */
@Override
public T removeLast() throws EmptyCollectionException {
    if(isEmpty()){
        throw new EmptyCollectionException("list");
    }

    T result=(T) tail.getElement();
    tail=tail.getNext();
    count--;
    modCount++;
    return result;
}

/**  
 * Removes and returns the specified element from this list. 
 *
 * @param targetElement the target element
 * @return the target element
 */
@Override
public T remove(T targetElement) throws EmptyCollectionException, ElementNotFoundException {
    if(isEmpty()){
        throw new EmptyCollectionException("list");
    }

    boolean found = false;
    SinglyLinkedNode<T> previous = null;
    SinglyLinkedNode<T> current = head;

    while (current != null && !found)
        if (targetElement.equals(current.getElement()))
            found = true;
        else
        {
            previous = current;
            current = current.getNext();
        }

    if (!found)
        throw new ElementNotFoundException("LinkedList");

    if (size() == 1)  // only one element in the list
        head = tail = null;
    else if (current.equals(head))  // target is at the head 
        head = current.getNext();
    else if (current.equals(tail))  // target is at the tail
    {
        tail = previous;
        tail.setNext(null);
    }
    else  // target is in the middle
        previous.setNext(current.getNext());

    count--;
    modCount++;
    return current.getElement();


}

/**  
 * Returns a reference to the head element in this list. 
 *
 * @return a reference to the head element in this list
 */
@Override
public T first() throws EmptyCollectionException {
    if(isEmpty()){
        throw new EmptyCollectionException("list");
    }

    T result=(T) head.getElement();
    return result;
}

/**  
 * Returns a reference to the tail element in this list. 
 *
 * @return a reference to the tail element in this list
 */
@Override
public T last() throws EmptyCollectionException {
    if(isEmpty()){
        throw new EmptyCollectionException("list");
    }

    T result=(T) tail.getElement();
    return result;
}

/**  
 * Returns true if this list contains the specified target element. 
 *
 * @param target the target that is being sought in the list
 * @return true if the list contains this element
 */
@Override
public boolean contains(T target) throws EmptyCollectionException {
    if(isEmpty()){
        throw new EmptyCollectionException("list");
    }
    for(T result:this){
        if(result.equals(target)){
            return true;
        }
    }
    return false;
}

/**  
 * Returns true if this list contains no elements. 
 *
 * @return true if this list contains no elements
 */
@Override
public boolean isEmpty() {
    return(head==null);
}

 /**  
 * Returns the number of elements in this list. 
 *
 * @return the integer representation of number of elements in this list
 */
@Override
public int size() {
    return count;
}

/**  
 * Returns an iterator for the elements in this list. 
 *
 * @return an iterator over the elements in this list
 */
@Override
public Iterator<T> iterator() {
    return new LinkedListIterator();
}


private class LinkedListIterator implements Iterator<T>
    {
        private int iteratorModCount;  // the number of elements in the collection
        private SinglyLinkedNode<T> current;  // the current position


    /**
     * Sets up this iterator using the specified items.
     *
     * @param collection  the collection the iterator will move over
     * @param size        the integer size of the collection
     */
    public LinkedListIterator()
    {
        current = head;
        iteratorModCount = modCount;
    }

    /**
     * Returns true if this iterator has at least one more element
     * to deliver in the iteration.
     *
     * @return  true if this iterator has at least one more element to deliver
     *          in the iteration
     * @throws  ConcurrentModificationException if the collection has changed
     *          while the iterator is in use
     */
    public boolean hasNext() throws ConcurrentModificationException
    {
        if (iteratorModCount != modCount) 
            throw new ConcurrentModificationException();

        return (current != null);
    }

    /**
     * Returns the next element in the iteration. If there are no
     * more elements in this iteration, a NoSuchElementException is
     * thrown.
     *
     * @return the next element in the iteration
     * @throws NoSuchElementException if the iterator is empty
     */
    public T next() throws ConcurrentModificationException
    {
        if (!hasNext())
            throw new NoSuchElementException();

        T result = current.getElement();
        current = current.getNext();
        return result;
    }

    /**
     * The remove operation is not supported.
     * 
     * @throws UnsupportedOperationException if the remove operation is called
     */
    public void remove() throws UnsupportedOperationException
    {
        throw new UnsupportedOperationException();
    }
}

}

这是LinkedOrderedList类:

    package animal;
/**
 * @author Sharon Umute 
 * Comp 139 001B
 * @param <T>
 */
public class LinkedOrderedList<T> extends LinkedList<T> implements OrderedListADT<T>{


    /**
     * Creates an empty list.
     */
    public LinkedOrderedList()
    {
        super();
    }

    /**
     * Adds the specified element to this list at the proper location
     *
     * @param element the element to be added to this list
     */
    @Override
    public void add(T element) {
        SinglyLinkedNode<T> node =new SinglyLinkedNode<>(element);
        SinglyLinkedNode<T> previous=null;
        SinglyLinkedNode<T> current=head;
        Animal animal;
        Animal animal2;
        int result;
        if(isEmpty()){
            tail = head = node;
        }else{
            int i=0;
            while( i<this.size()){
                animal=(Animal) current.getElement();
                animal2=(Animal) node.getElement();
                result=animal.getName().compareTo(animal2.getName());
                if((result==-1)&&(current!=head)&&(current!=tail)){
                    previous=current;
                    current=current.getNext();
                    i++;
                }else if((result==1)&&(current!=head)&&(current!=tail)){
                    previous.setNext(node);
                }else if((result==0)&&(current!=head)&&(current!=tail)){
                    i++;
                }
                if((current==head)||((size()==1)&&(result==1))){
                    node.setNext(head);
                    head=node;
                }else if((current==tail)||((size()==1)&&(result==-1))){
                    tail.setNext(node);
                    tail=node;
                }
            }
        }
    }
}

这是一个名为SimpleGUI的GUI,除了actionPerformed之外我不允许改变任何内容所以这是显示的唯一部分:

    @Override
  public void actionPerformed(ActionEvent ev) throws NullPointerException {
    Object object = ev.getSource();
        if (object == addReptileButton) {
            try {
                useA= new Reptile(namePanel.getText(), weightPanel.getValue(), 
                        agePanel.getValue(),reptileLengthPanel.getValue());
            } catch (InvalidNameException | InvalidWeightException ex) {
                Logger.getLogger(SimpleGUI.class.getName()).log(Level.SEVERE, 
                        null, ex);
            }

            try{
                list.add(useA);
            }catch(EmptyCollectionException|NullPointerException ec){
                JOptionPane.showMessageDialog(null, "The List isEmpty", 
                        "Input Error",
                    JOptionPane.ERROR_MESSAGE);
            }
        }else if (object == addMammalButton) {
            try {
                useA= new Mammal(namePanel.getText(), weightPanel.getValue(), 
                        agePanel.getValue(),mammalColorPanel.getText());
            } catch (InvalidNameException | InvalidWeightException ex) {
                Logger.getLogger(SimpleGUI.class.getName()).log(Level.SEVERE, 
                        null, ex);
            }
            try{
                list.add(useA);
            }catch(EmptyCollectionException|NullPointerException  ec){
                JOptionPane.showMessageDialog(null, "The List is Empty", 
                        "Input Error",
                    JOptionPane.ERROR_MESSAGE);
            }
        }else if (object == RemoveFirst) { 
            try{
                Animal current = (Animal) list.removeFirst();
            }catch(EmptyCollectionException|NullPointerException  ec){
                JOptionPane.showMessageDialog(null, "The List is Empty", 
                        "Input Error",
                    JOptionPane.ERROR_MESSAGE);
            }
        }else if (object == RemoveLast) {
            try{
                Animal current = (Animal) list.removeLast();
            }catch(EmptyCollectionException|NullPointerException  ec){
                JOptionPane.showMessageDialog(null, "The list is Empty", 
                        "Input Error",
                    JOptionPane.ERROR_MESSAGE);
            }
        } else if (object == displayAnimalsButton) {
            verifyArea.setText(" ");
            try{
                for(int j=0; j<10; j++){
                    Animal result = (Animal) list.removeFirst();
                    verifyArea.append(result.toString());
                    list.add(result);
                }
            }catch(EmptyCollectionException ex){
                verifyArea.append(" ");
            }
        }

    }

有人可以告诉我这里的问题是什么以及如何解决它。我真的很感激。

1 个答案:

答案 0 :(得分:0)

我不知道这是否是您问题的原因,但您显示列表的方式有点疯狂。如果您实施任何尺寸,添加或删除都有任何问题,那么每次您尝试显示列表时都可以将其删除。

更好的方法是使用列表迭代器。

但更一般地说,您需要学习如何在IDE中使用调试器。使用调试器是每个程序员需要掌握的基本技能。一个无法调试代码的程序员对雇主来说基本没用。

您需要学习的另一件事是如何编写单元测试。