M
M
mr jeery2020-06-11 22:53:23
Java
mr jeery, 2020-06-11 22:53:23

Why type error when using Generic?

I'm learning Java and algorithms along the way, I ran into an error, help me figure it out
. I'm passing the desired type to the class, what's the problem?

class Node<T> {

    T element;
    Node<T> next;

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

public class LinkedList<T> {

    Node<T> head;

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

    public T getValueById(Number id) {
        Number counter = 0;
        Node<T> searchingNode = this.head;

        while (id != counter) {
            searchingNode = searchingNode.next;

            if (searchingNode == null) {
                return -1; // Здесь ошибка Required type: T; Provided: int
            }
        }

        return searchingNode.element;
    }
    
}


public class Main {

    public static void main(String[] args) {

        Node<Integer> head = new Node(10, null);
        LinkedList<Integer> list = new LinkedList(head);

        System.out.print(list.getValueById(0));
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergei Chamkin, 2020-06-11
@jeerjmin

You return 1, which is an int, but you promise that the function will return type T.
Return null or return Object

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question