java - 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;
}
}
解决方案
这里:
if(currentElm.equals(searchedElem.getObj()))
您正在尝试将currentElm
作为节点的 与searchedElem.getObj()
作为节点内部的值进行比较。
大概你的意思是
if (currentElm.getObj().equals(searchElement))
推荐阅读
- install4j - Install4j 需要时间来清理自己
- java - org.xml.sax.SAXParseException;尝试从请求中获取 xml 输入时文件过早结束
- node.js - 如何在 NodeJS 中使用带有图表和谷歌地图的 html 生成 PDF
- rust - Rust 中结构字段的多态更新
- android - Facebook 广告活动未显示应用安装数据
- c# - 使用 Html.Raw 时如何运行 Html 和 Url 助手 - ASP NET MVC
- excel - Excel:如何将千 (k) 和百万 ($m) 的缩写转换为数值?
- go - Go 中并发数据收集的最佳方式是什么,为什么?
- java - 如何完全阻止 JUnit 套件的执行?
- php - 我正在尝试使用 php 上传音乐和图像文件并插入数据表,但我的代码不起作用