Home >Java >Type mismatch: cannot convert from DLL.Node to DLL.Node

Type mismatch: cannot convert from DLL.Node to DLL.Node

王林
王林forward
2024-02-22 13:10:10845browse

php editor Yuzi brings you a selection of java Q&A. Today’s question: Type mismatch: Unable to convert from DLL.Node to DLL.Node. The problem usually involves compilation errors caused by generic type erasure and needs to be resolved by type conversion or code redesign. In Java, the actual type of a generic is erased after compilation, causing the compiler to not accurately identify the type. By understanding the principle of generic erasure and flexible use of type conversion, such problems can be effectively solved.

Question content

I am trying to implement a doubly linked list with nested node classes. Due to the generic nature of the class I'm getting a type mismatch error. Since the nested class is not a static class, I thought it would use the generic type operator from the top class.

public class DLL <E> {
    
    public class Node<E>{
        private E element;
        private Node<E> prev;
        private Node<E> next;
        
        public <E> Node (E element, Node <E> prev, Node<E> next){
            this.element = element; // Error: Type mismatch: cannot convert from E to E
            this.prev = prev; // Error: Type mismatch: cannot convert from DLL<E>.Node<E> to DLL<E>.Node<E>
            this.next = next;// Error: Type mismatch: cannot convert from DLL<E>.Node<E> to DLL<E>.Node<E>
        }

Any help would be great!

Solution

Instead of redeclaring the generic type e. The node constructor should use the generic type e from the external dllca37468c879b0f5f3f64e26b1333f6f6 class. The solution is as follows:

public class DLL<E> {
    
    public class Node {
        private E element;
        private Node prev;
        private Node next;
        
        public Node(E element, Node prev, Node next) {
            this.element = element;
            this.prev = prev;
            this.next = next;
        }
    }

}

The above is the detailed content of Type mismatch: cannot convert from DLL.Node to DLL.Node. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete