1
link.removeFirstOccurrence(new Integer(9));

This is what my professor wants, but it only works when I pass values in like link.removeFirstOccurrence(9);. Any advice?

public boolean removeFirstOccurrence(Object obj) { 
    DNode<E> current = head;
    DNode<E> temp = null;

    if(current != null && current.data == obj) {
        head = current.next;
        return true;

    }
    while(current != null && current.data != obj) {
        temp = current;
        current = current.next;
    }
     if(current == null) {
         return false;
     }

     temp.next = current.next;
     current.next.previous = current.previous;

     return true;
  }
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Slhx89
  • 11
  • 2
  • it needs a little bit explanation – The Scientific Method Mar 03 '20 at 02:49
  • Perhaps this SO question will help. [java - how to delete a node from linkedlist?](https://stackoverflow.com/questions/22902924/java-how-to-delete-a-node-from-linkedlist) And also this one. [What does equals(Object obj) do?](https://stackoverflow.com/questions/8338326/what-does-equalsobject-obj-do) – Abra Mar 03 '20 at 02:50

1 Answers1

0

Your code has problem with Java Object comparison. To compare values, you can use "==" operator for primitive data type but you have to use "equals()" method for non primitive data types

Below are updated code:

public boolean removeFirstOccurrence(Object obj) {
    DNode<E> current = head;
    DNode<E> temp = null;

    if (current != null && current.data != null && current.data.equals(obj)) {
        head = current.next;
        return true;

    }
    while (current != null && current.data != null && !current.data.equals(obj)) {
        temp = current;
        current = current.next;
    }
    if (current == null || current.data == null) {
        return false;
    }

    temp.next = current.next;
    current.next.previous = current.previous;

    return true;
}
Kevin Le
  • 266
  • 1
  • 5