首页 > 解决方案 > LinkedList .equals vs == 整数上的运算符

问题描述

我正在调试我编写的 LinkedList 的这个 contains 方法,并且 Integer 类型 30 的比较没有被包含在 contains 方法中。据我了解, == 运算符用于比较内存中的地址,而 .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;
    }
}

标签: javalinked-listequalscontains

解决方案


这里:

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

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

大概你的意思是

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

推荐阅读