I'm debugging this contains method for a LinkedList that I coded and the comparison of the Integer type 30 is not getting caught in the contains method. From my understanding, the == operator is used to compare addresses in memory and the .equals operator is used to compare equivalency. I have messed around a bit and can't seem to find out why comparing the Integer value of 30 that is passed into the contains method it is still not catching an Integer 30 that was added with the add method when entered.
Here is the code
list build and populate
//constructing the list
MyBag<Integer> bagLinked = new MyBag<>();
DynamicList<Integer> bagListlinked = new LinkedList<>();
bagLinked.setList(bagListlinked);
//adding integers to the list
for (int i=1; i<=3; i++)
bagLinked.add(i*10);
Contains Method
// Integer value "30" is passed into contains method and then contains
//is called for bagLinked List
public boolean contains(T searchElement) {
boolean elemExists =false;
LLNode<T> searchedElem = new LLNode<>(searchElement);
LLNode<T> currentElm = this.head;
while(currentElm.getObj() != null){
if(currentElm.equals(searchedElem.getObj())){
elemExists =true;
break;
}
currentElm = currentElm.nextPointer;
}//problem with get object its not comparing the value of 30 just the mem address
return elemExists;
}
Node Class
public class LLNode<T> {
T obj;
LLNode<T> previousPointer;
LLNode<T> nextPointer;
int index;
public LLNode(T obj){
this.obj = obj;
this.index=0;
}
public T getObj() {
return obj;
}
public LLNode<T> getPreviousPointer() {
return previousPointer;
}
public LLNode<T> getNextPointer() {
return nextPointer;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
Here:
if(currentElm.equals(searchedElem.getObj()))
You are trying to compare currentElm
, which is a Node, to searchedElem.getObj()
, which is a value inside a Node.
Presumably you mean something like
if (currentElm.getObj().equals(searchElement))