2
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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Karan8404
  • 23
  • 3
  • "I know that this warning must mean that my code can somehow break during runtime" No it doesn't always mean that. The cast is safe. – Sweeper Nov 27 '22 at 12:08
  • So is there any way to "safely" cast it which removes the warning or do i have suppress the warning afterall? I am still learning java so this may explain my discomfort with warnings. I just want to know if suppressing the warning here is the best practice or there is more i can do. – Karan8404 Nov 27 '22 at 12:18
  • 1
    `Node` should be a (static) nested class, not an inner class, and have its own type parameter. – Mark Rotteveel Nov 27 '22 at 15:22

1 Answers1

3

You could use this to avoid the cast warning

if (!(obj instanceof LinkedList<?>.Node)) return false;
LinkedList<?>.Node node = (LinkedList<?>.Node) obj;
Thomas.L
  • 321
  • 1
  • 6