Java LinkedOrderedList和LinkedList实现

Java LinkedOrderedList和LinkedList实现,java,linked-list,Java,Linked List,所以我应该创建一个程序来创建动物列表。程序按名称对它们进行分类,并按字母顺序将它们放入列表中。但每次我点击“显示动物”按钮时,它都没有显示任何内容,我发现这是list.size()的问题,所以我将其改为整数10来测试它,它显示了,但它只显示添加的第一只动物。我不确定问题出在哪里,我真的很困惑,以下是我的代码: 这是LinkedList类 package animal; import exceptions.ElementNotFoundException; import exceptions.Em

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

这是LinkedList类

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();
    }
}

}

有人能告诉我这里有什么问题以及如何解决吗。非常感谢。

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

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

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


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

我认为不太可能有人想涉猎所有这些代码。我建议你使用一个调试器来逐步检查你的代码,看看它出了什么问题。“所以我把它改成了整数10来测试它,它显示了,但它只显示了添加的第一个动物。”。你预计会有多少动物?你能添加一个“n”类动物的链表,看看你错在哪里吗。不确定为什么在操作显示“显示”时调用“removeFirst”。
    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;
                }
            }
        }
    }
}
    @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(" ");
            }
        }

    }