gpt4 book ai didi

java - 链表的 equals 方法不起作用

转载 作者:行者123 更新时间:2023-12-02 02:55:54 25 4
gpt4 key购买 nike

我在 List 类中实现删除方法时遇到问题。我首先将对象写入文件,然后检索这些对象并将它们放入链接列表中。然而,当我尝试通过检查整个链接列表来检查相等性时,即使我确定该对象在那里,我也得不到匹配项。我什至无法让 .equals 工作。

package ProjectOne;

public class List<T> {
private LLNode<T> list;
private int numberOfNodes = 0;
private LLNode<T> location;
private LLNode<T> previous;
protected boolean found;
public List() {
list = null;
}
public void add(T element) {
if (numberOfNodes == 0) {
list = new LLNode<T>(element);
numberOfNodes++;
}
else {
LLNode<T> newNode = new LLNode<T>(element);
newNode.setLink(list);
list = newNode;
}
}


public void find(T target) {
location = list;
found = false;
while(location !=null) {
System.out.println(target.equals(location.getInfo()));
if(location.getInfo().equals(target)) {
found = true;
return;
}
else {
previous = location;
location = location.getLink();
}
}
}

public boolean remove(T element) {
this.find(element);
if(found) {
if(list == location) list = list.getLink();
else previous.setLink(location.getLink());
}
return found;
}

public LLNode<T> getList() {
return list;
}



public String toString() {
LLNode<T> currentNode = list;
String info = "";
while(currentNode !=null) {
info +=currentNode.getInfo();
currentNode = currentNode.getLink();
}
return info;
}

}

这些是我写入文件的众多对象之一

 Patient p1 = new Patient("Alex", "1123 metropolitan", new Date("11/20/1997"));
p1.setFirstVisit(new Date("11/20/1997"));
p1.setHeight(72);
p1.setLastVisit(new Date("11/20/1997"));
p1.setWeight(200);
out.writeObject(p1);

Patient p2 = new Patient("John", "200 avenue of americas", new Date("12/20/1999"));
p2.setFirstVisit(new Date("11/11/2005"));
p2.setHeight(5);
p2.setLastVisit(new Date("11/21/2010"));
p2.setWeight(150);
out.writeObject(p2);

Patient p3 = new Patient("Sarah", "Park avenue", new Date("09/07/1960"));
p3.setFirstVisit(new Date("05/11/1977"));
p3.setHeight(75);
p3.setLastVisit(new Date("01/21/2017"));
p3.setWeight(110);
out.writeObject(p3);

Patient p4 = new Patient("Malcolm", "56street", new Date("05/28/1977"));
p4.setFirstVisit(new Date("01/11/1990"));
p4.setHeight(75);
p4.setLastVisit(new Date("8/21/2016"));
p4.setWeight(155);
out.writeObject(p4);

但是,当我调用 System.out.println(list.remove(p1));我得到输出错误的错误的错误的错误的错误的最后一个是方法的返回结果,前四个只是尝试调试。

最佳答案

确保您重写 Patient 类中的 equals 和 hashcode 方法。

关于java - 链表的 equals 方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43083882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com