LinkedList .equals vs == 整数运算符

LinkedList .equals vs == operator on Integers

我正在调试我编写的 LinkedList 的这个 contains 方法,并且 contains 方法中没有捕获整数类型 30 的比较。据我了解, == 运算符用于比较内存中的地址, .equals 运算符用于比较等价性。我搞砸了一点,似乎无法找出为什么比较传递给 contains 方法的 Integer 值 30 它仍然没有捕获输入时使用 add 方法添加的 Integer 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;
}

节点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;
    }
}

这里:

if(currentElm.equals(searchedElem.getObj()))

您正在尝试将节点 currentElm 与节点内的值 searchedElem.getObj() 进行比较。

大概你的意思是

if (currentElm.getObj().equals(searchElement))