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

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

王林
Release: 2024-02-22 13:10:10
forward
850 people have browsed it

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>
        }
Copy after login

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 dll<e> 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;
        }
    }

}
Copy after login

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template