java链接列表。等于vs==整数上的运算符
我正在为我编码的LinkedList调试这个contains方法,并且contains方法中没有捕获整数类型30的比较。根据我的理解,==运算符用于比较内存中的地址和。equals运算符用于比较等效性。我搞砸了一点,似乎不明白为什么在比较传递到contains方法的整数值30时,它仍然没有捕捉到输入时与add方法一起添加的整数30
这是密码
列出构建和填充
//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);
包含方法
// 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;
}
节点类
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;
}
}
# 1 楼答案
这里:
您正在尝试将节点
currentElm
与节点内的值searchedElem.getObj()
进行比较你大概是说