Home > front end >  Type casting to a class nested inside a generic class
Type casting to a class nested inside a generic class

Time:11-28

package LinkedList;

public class Linkedlist<T> {
    private int size;
    Node head;
    Node tail;

    public Linkedlist() {// default constructor
        size = 0;
        head = null;
        tail = null;
    }

    public class Node {// Node class
        T data;// current node data
        Node next;// reference to next node
        Node prev;// reference to previous node

        public Node(T data) {// def constructor
            this.data = data;
            next = null;
            prev = null;
        }

        @Override // to check equality of two nodes
        public boolean equals(Object obj) {
            if (this == obj)// checks if both have same reference
                return true;
            if (obj == null ||this==null || this.getClass() != obj.getClass())
                return false;
            @SuppressWarnings("unchecked")//casting obj to node gives a unchecked cast warning.
            Node n=((Node)obj);
            if(!(this.data==n.data))
                return false;
            return true; 
        }

As in the code above, I have a generic class Linkedlist which nests a Node class. The functionality of the code is very obvious, I'm trying to create a doubly linked list.

The problem is that in the equals function in the Node class, I am typecasting the object obj to a Node which gives an unchecked cast warning which I have currently suppressed. The autogenerated equals function from Visual Studio Code gives this same warning. I know that this warning must mean that my code can somehow break during runtime, but I don't know how and I am new to generics and programming in general. Is there any way to resolve this warning?

CodePudding user response:

You could use this to avoid the cast warning

if (!(obj instanceof LinkedList<?>.Node)) return false;
LinkedList<?>.Node node = (LinkedList<?>.Node) obj;
  • Related