一直在寻找我的问题的解决方案。已经阅读了很多关于覆盖等于正确比较链表的节点但已经卡住了。基本上我试图搜索我的列表,找到一个等于它的节点并删除它。我找到了查看链表的方法,但是当我返回节点时,它只是乱码。我试图找到一种方法将它变成一个字符串,并将其与另一个字符串进行比较。无论如何这里是代码和我的equals方法,目前无法正常工作。
public class MagazineList {
private MagazineNode list;
private Object obj;
public MagazineList(){
list = null;
}
public void add(Magazine mag){
MagazineNode node = new MagazineNode(mag);
MagazineNode current;
if(list==null)
list = node;
else{
current = list;
while(current.next != null)
current = current.next;
current.next = node;
}
}
public void insert(Magazine mag)
{
MagazineNode node = new MagazineNode (mag);
// make the new first node point to the current root
node.next=list;
// update the root to the new first node
list=node;
}
public void deleteAll(){
if(list == null){
}
else{
list = null;
}
}
public void delete (Magazine mag) {
MagazineNode current = this.list;
MagazineNode before;
//if is the first element
if (current.equals(mag)) {
this.list = current.next;
return; //ending the method
}
before = current;
//while there are elements in the list
while ((current = current.next) != null) {
//if is the current element
if (current.equals(mag)) {
before.next = current.next;
return; //endind the method
}
before = current;
}
//it isnt in the list
}
public boolean equals(Object other) {
System.out.println("Here in equals" + other + this);
// Not strictly necessary, but often a good optimization
if (this == other)
return true;
else{
return false;
}
}
@ Override
public String toString(){
String result = " ";
MagazineNode current = list;
while (current != null){
result += current.magazine + "\n";
current = current.next;
}
return result;
}
private class MagazineNode {
public Magazine magazine;
public MagazineNode next;
public MagazineNode(Magazine mag){
magazine = mag;
next = null;
}
}
}
答案 0 :(得分:5)
您的删除方法看起来不错,但您不应将MagazineNode与杂志进行比较。您应该将杂志与杂志进行比较。
将if (current.equals(mag))
替换为if (current.magazine.equals(mag))
。
答案 1 :(得分:1)
好的 - 请注意,你的equals方法只是重新实现== identity equals。
这意味着如果other
不是同一个Magazine对象,则会失败。如果这就是你想要的那样好,但通常你想选择杂志中的属性。
因此,如果杂志有String title
,那么在你的equals方法中,你会做类似的事情:
if (magazine instanceof Magazine && magazine.getTitle().equals(other.getTitle()) returnval = true;
另外,请参阅Joshua Bloch的Effective Java,以获得对此的精彩描述。每次重写equals方法时,您还希望覆盖hashCode方法。他们走到一起,他描述了原因。
希望这会有所帮助。
答案 2 :(得分:1)
如果您使用的是eclipse,请使用此功能:Eclipse - >来源 - >生成hashCode()和equals()。并研究其实施。这将有助于您了解如何编写equals()和hashCode()。祝你好运。