Hello what is wrong with my add method? It says there is a bad operand type for
ID: 3809317 • Letter: H
Question
Hello what is wrong with my add method? It says there is a bad operand type for binary operators but Im not sure how to fix it to allow it to compare. The parts im referring to are bolded
public class MyOrderedLinkedList extends MyAbstractList {
private Node head, tail;
public MyOrderedLinkedList() {
}
public MyOrderedLinkedList(E[] objects) {
super(objects);
}
public void add(E e) {
Node newNode = new Node(e);// Create a new node
if (head == null || tail == null) { // the new node is the only node in list
newNode.next = head; // link the new node with the head
head = newNode; // head points to the new node
if (tail == null) {
tail = head;
}
} else if (e >= tail.element) { // new node is greater then tail
tail.next = newNode; // Link the new with the last node
tail = tail.next; // tail now points to the last node
} else if (e <= head.element) { // new node is smaller then head
newNode.next = head; // link the new node with the head
head = newNode; // head points to the new node
} else {
Node current = head;
for (int i = 1; i <= size; i++) {
if (current.element >= e) {
break;
}
current = current.next;
}
Node temp = current.next;
current.next = new Node(e);
(current.next).next = temp;
}
size++; // Increase size
}
private static class Node {
E element;
Node next;
public Node(E element) {
this.element = element;
}
} // end of Node
}
Explanation / Answer
Hi, you can not compare using simple '==' operator.
For reference type, it only compares whether both references point to same object ot not. It will not comare the content of the objects.
For that you need to use compareTo method.
To available compareTo method for type 'E', E should be type of comparable, means E should implements Comparable interface.
I am assuming that E implements Comparable interface, the find my implementation of add method:
public void add(E e) {
Node newNode = new Node(e);// Create a new node
if (head == null || tail == null) { // the new node is the only node in list
newNode.next = head; // link the new node with the head
head = newNode; // head points to the new node
if (tail == null) {
tail = head;
}
} else if (e.compareTo(tail.element) >= 0) { // new node is greater then tail
tail.next = newNode; // Link the new with the last node
tail = tail.next; // tail now points to the last node
} else if (e.compareTo(head.element) <= 0) { // new node is smaller then head
newNode.next = head; // link the new node with the head
head = newNode; // head points to the new node
} else {
Node current = head;
for (int i = 1; i <= size; i++) {
if (current.element.compareTo(e) >= 0) {
break;
}
current = current.next;
}
Node temp = current.next;
current.next = new Node(e);
(current.next).next = temp;
}
size++; // Increase size
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.