嗨,equals 方法用于比较用户定义的对象。似乎它们是按内存位置进行比较,而不是按整数对象内的数据进行比较。在线资源说 equals() 方法按数据进行比较。我很困惑。我将附加代码,它是一个带尾的单链表实现。我感到困惑的地方是在 remove() 方法中,我会注意下面的行。谢谢
public class Node<T>
{
private T element;
private Node next;
public Node() //constructor creates an empty node
{
this.element=null;
this.next=null;
}
public Node(T element) //overloaded constructor creates a node with element to hold
{
this.element=element;
this.next=null;
}
public Node<T> getNext()
{
return next;
}
public void setNext(Node<T> next)
{A
this.next=next;
}
public T getElement()
{
return this.element;
}
public void setElement(T element)
{
this.element=element;
}
}
public abstract class LinkedList<T>
{
protected int count;
protected Node<T> head, tail;
protected int modCount;
public LinkedList() //creates an empty list
{
count=0;
head=tail=null;
modCount=0;
}
public T remove(T targetElement)
{
if(isEmpty())
throw new EmptyCollectionException("LinkedList");
boolean found=false;
Node<T> previous = null;
Node<T> tempNode=head;
while(tempNode != null && !found)
if(targetElement.equals(tempNode.getElement())) //here compares by data?
found=true;
else
{
previous =tempNode;
tempNode=tempNode.getNext();
}
if(!found)
{
System.out.println("element not found ");
return null;
}
if(size()==1)
{
head=tail=null;
}
else if(tempNode.equals(head)) //here is where comparison is made by memory
head=tempNode.getNext();
else if(tempNode.equals(tail)) //here
{
tail=previous;
tail.setNext(null);
}
else
previous.setNext(tempNode.getNext());
count--;
modCount++;
return tempNode.getElement();
}
public boolean isEmpty()
{
return count <=0;
}
public int size()
{
return count;
}
@Override
public String toString()
{
String str = "";
Node<T> tempNode = head;
while(tempNode != null)
{
str = str + tempNode.getElement() + " ";
tempNode = tempNode.getNext();
}
return str;
}
}
public class Main
{
public static void main(String[] args)
{
LinkedUnorderedList<Integer> list = new LinkedUnorderedList<Integer>();
list.addToRear(5);
list.addToRear(6);
list.addToRear(6);
list.remove(6);
System.out.println(list);
}
}
public class LinkedUnorderedList<T> extends LinkedList<T>
{
public LinkedUnorderedList()
{
super(); //sets up super class instance data
}
}