我在List类中实现remove方法时遇到问题。我首先将对象写入文件,然后我将检索这些对象并将它们放入链接列表中。但是,当我尝试通过遍历整个链表检查相等性时,我得到的不是匹配,即使我确定对象在那里。我甚至无法让.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));
时
我得到了输出
假
假
假
假
假
最后一个是方法的返回结果,前四个只是试图调试。
答案 0 :(得分:2)
确保在Patient类中覆盖equals和hashcode方法。