Тип T не является действительной заменой ограниченного параметра ` > - PullRequest
0 голосов
/ 05 августа 2020
package einfuehrung.knodenUndListeKopie;

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

public class List<T> {

    private class ListIterator<K> implements Iterator<T> {
        private Node<T> node = null;

        public ListIterator() {
            node = head;
        }

        @Override
        public boolean hasNext() {
            return node.getNext() != null;
        }

        @Override
        public T next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            node = node.getNext();
            T obj = node.getObject();
            return obj;
        }

    }

    public Iterator<T> iterator() {
        ListIterator<T> iter = new ListIterator<T>();
        return iter;
    }

    private Node<T> head;

    public List() {
        this.head = new Node<T>();
    }

    public Node<T> getHead() {
        return head;
    }

    public void setHead(Node<T> head) {
        this.head = head;
    }

    public boolean isEmpty() {
        return head.getNext() == null;
    }

    public void addFirst(T element) {
        Node<T> node = new Node<T>();
        Node<T> nextNode = head.getNext();
        node.setObject(element);
        node.setNext(nextNode);
        head.setNext(node);

    }

    public void addLast(T element) {
        Node<T> node = new Node<T>();
        Node<T> lastNode = head;

        while (lastNode.getNext() != null) {
            lastNode = lastNode.getNext();
        }

        lastNode.setNext(node);
        node.setNext(null);
        node.setObject(element);
    }

    public Object removeFirst() {
        Object solution;
        if (isEmpty()) {
            solution = null;
        }
        Node<T> node = head.getNext();
        Node<T> nextNode = node.getNext();
        solution = node.getObject();
        head.setNext(nextNode);

        return solution;
    }

    public Object removeLast() {
        Object solution;
        if (isEmpty()) {
            solution = null;
        }

        Node<T> beforeLastNode = head;
        Node<T> lastNode;

        while (beforeLastNode.getNext().getNext() != null) {
            beforeLastNode = beforeLastNode.getNext();
        }

        lastNode = beforeLastNode.getNext();
        solution = lastNode.getObject();
        beforeLastNode.setNext(null);

        return solution;
    }

    /**
     * It does not delete the node, where the element is saved.
     * 
     * @return first element of list
     */
    public Object getFirstElement() {

        return head.getNext().getObject();
    }

}

Первый выше - мой List-Class.

    package einfuehrung.knodenUndListeKopie;

import java.util.Collection;

public class Node<T extends Collection<?>> {

    private Node<T> next;
    private T object;

    public Node() {

    }

    public Node(Node<T> next, T object) {
        this.next = next;
        this.object = object;
    }

    public Node<T> getNext() {
        return next;
    }

    public void setNext(Node<T> next) {
        this.next = next;
    }

    public T getObject() {
        return object;
    }

    public void setObject(T object) {
        this.object = object;
    }
    
    public int countAllElements() {
        int solution;
        solution = object.size();
        if (this.next != null) {
            solution += this.next.countAllElements();
        }
        
        
        
        return solution;
    }

}

Второй класс - мой Node-Class.

Описание проблемы. Все было хорошо после того, как я ограничил параметр T в своем классе узла. Мне пришлось, потому что T нужно было реализовать метод размера. Это было необходимо для метода countAllElements() в Node-Class. В моем классе списка я получаю сообщение об ошибке: «Тип T не является действительной заменой ограниченного параметра <T extends Collection<?>> типа Node<T>. Сообщение об ошибке появляется везде, где я использую экземпляр моего объекта из типа Node<T>.

Надеюсь, я сделал все правильно в этом вопросе, разместив здесь свой код. Извините за смену регистра, я живу в Германии. Я не знаю, что делает мой компьютер D:.

Отредактировано: Извините, ребята, я забыл изменить заголовок. Я его изменил.

1 Ответ

0 голосов
/ 05 августа 2020

В нынешнем виде вы противоречите себе: вы говорите, что ваши Node s могут содержать любые T в вашем List классе, но ваш Node класс говорит, что они могут содержать любые Collection.

Итак, вам нужно либо:

  • Go через все Node<T> в классе List, заменив их чем-то списком Node<Collection<T>> , Node<List<T>> et c

  • Удалите ограничение на параметр типа в классе Node и предоставьте ToIntFunction<? super T> методу countAllElements, чтобы вы могли чтобы сказать «вот как вы« считаете »T»:

    public int countAllElements(ToIntFunction<? super T> counter) {
      int solution = counter.apply(object);
      if (this.next != null) {
        solution += this.next.countAllElements(counter);
      }   
      return solution;
    }
    
...