I'm implementing a list link in the stack. The program successfully passes all the required tests, but I encounter this warning. There is no disruption in the implementation of the program, but I am looking to eliminate this problem.
Can you tell me how to fix it by editing the code in the Equals method?
Unchecked cast: 'java.lang.Object' to 'LinkedStack'
public final class LinkedStack<E> implements Stack<E> { private Node head = null; private int size = 0; @Override public int size() { return size; } @Override public boolean isEmpty() { return size == 0; } @Override public void clear() { head = null; size = 0; } @Override public boolean contains(E e) { for (int i = 0; i < size; i++) { E temp = pop(); if (temp.equals(e)) { return true; } } return false; } @Override public E top() throws StackEmptyException { if (size == 0) { throw new StackEmptyException(); } return head.element; } @Override public void push(E e) { head = new Node(e, head); size++; } @Override public E pop() throws StackEmptyException { if (size == 0) { throw new StackEmptyException(); } E temp = head.element; head = head.next; size--; return temp; } public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; LinkedStack<E> that = (LinkedStack<E>) o; if (that.size() != this.size()) return false; Node j = that.head; int counter = 0; for (Node i = head; counter < size; i = i.next, j = j.next) { if (i.element == null && j.element == null) { counter++; continue; } if ((i.element != null) && (j.element != null)) { if (!i.element.equals(j.element)) { return false; } } else { return false; } counter++; } return true; } @Override public int hashCode() { int resultat = 1; int counter = 0; for (Node i = head; counter < size; i = i.next) { if (i.element == null) { counter++; continue; } resultat = resultat * i.element.hashCode(); counter++; } return resultat; } protected class Node { private final E element; private final Node next; protected Node(final E element, final Node next) { this.element = element; this.next = next; } } }
containsmethod empties out the entire stack in the process of checking whether the stack contains the element. That's... bad.