Класс LinkedList. (ReflectiveOperationException)

1

Я изучаю Java SE и в настоящее время в простых связанных списках (стр. 687/1047 от Savuth Absolute Java).

Я застрял в LinkList экземпляра LinkList в основном методе моего демонстрационного класса:

LinkedList1 list = new LinkedList1();

Я попытался использовать точку останова, и это указывает на ReflectiveOperationException. Это код:

public class Node1 
{  
    private String item;
    private int count;
    private Node1 link;

    public Node1()
    {
        link = null;
        item = null;
        count = 0;

    }

    public Node1(String newItem, int newCount, Node1 linkValue)
    {
        setData(newItem, newCount);
        link = linkValue;
    }

    public void setData(String newItem, int newCount)
    {
        item = newItem;
        count = newCount;
    }

    public void setLink(Node1 newLink)
    {
        link = newLink;
    }

    public String getItem()
    {
        return item;
    }

    public int getCount()
    {
        return count;
    }

    public Node1 getLink()
    {
        return link;
    }
}

Это класс LinkedList1:

public class LinkedList1 
{
    private Node1 head;

    public LinkedList1()
    {
        head = null;
    }

    /**
     * Adds a node at the start of the list with the specified data.
     * The added node will be the first node in the list.
     */
    public void add(String itemName, int itemCount)
    {
        head = new Node1(itemName, itemCount, head);
    }


    /**
     * Removes the head node and returns true if the list contains at least
     * one node. Returns false if the list is empty.
     */
    public boolean deleteHeadNode()
    {

        if (head != null)
        {
            head = head.getLink();
            return true;
        }
        else
            return false;
    }

    /**
     * Returns the number of nodes in the list.
     */
    public int size()
    {
        int count = 0;
        Node1 position = head;
        while (position != null)
        {
            count++;
            head = position.getLink();
        }

        return count;
    }


    public boolean contains(String item)
    {
        return (find(item) != null);
    }


    /**
     * Finds the first node containing the target item, and returns a
     * reference to that node. If the target is not in the list, null is returned.
     */
    public Node1 find(String target)
    {
        Node1 position = head;
        String itemAtPosition;
        while(position != null)
        {
            itemAtPosition = position.getItem();
            if(itemAtPosition.equals(target))
            {
                return position;

            }
            position = position.getLink();
        }

        return null; //target was not found
    }


    public void outputList()
    {

        Node1 position = head;
        while (position != null)
        {
            System.out.println(position.getItem() + " " + position.getCount());
            position = position.getLink();
        }
    }
}

Я думаю, что проблема имеет какое-то отношение к конструктору Node1 имеющему ссылку-член типа Node1. Я пытаюсь понять, как работают эти структуры данных, а не просто использовать встроенные ArrayList (и API) для моих проектов. Можете ли вы, ребята, взглянуть и указать мне в правильном направлении. Любая помощь будет очень высоко ценится.

Это мой основной метод.

public class LinkedListDemo 
{
    public static void main(String[] args) 
    {
        try
        {
            LinkedList1 list = new LinkedList1();

            list.add("apples", 1);
            list.add("bananas", 2);
            list.add("cantaloupe", 3);
            System.out.println("List has "+ list.size() + " nodes.");
            list.outputList();
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}
  • 1
    Не могли бы вы опубликовать код, показывающий, где вы вызываете конструктор? Я предполагаю, что это в некотором методе main ()
  • 1
    Я только что выполнил ваш код и не получил никаких исключений, вы должны опубликовать ваш основной метод.
Показать ещё 5 комментариев
Теги:
list

1 ответ

3
Лучший ответ

Метод size содержит бесконечный цикл, который объясняет, почему выходы никогда не достигаются.

while (position != null)
{
    count++;
    head = position.getLink();
}

Вы зацикливаете до тех пор, пока позиция не станет нулевой, но никогда не назначайте что-либо позиции и вместо этого назначайте ее голове. Вместо этого вы хотите сделать

while (position != null)
{
    count++;
    position = position.getLink();
}

Теперь вы получите результат

List has 3 nodes.
cantaloupe 3
bananas 2
apples 1

Ещё вопросы

Сообщество Overcoder
Наверх
Меню