这是我的equals方法的实现。有人可以检查一下,让我知道它是否有用或如何改进它?
public boolean equals(Object o) {
if (o == null) return false;
if (getClass() != o.getClass())
return false;
CircularlyLinkedList other = (CircularlyLinkedList) o;
if (size != other.size)
return false;
if (tail != other.tail)
return false;
Node walkA = tail.getNext();
Node walkB = other.tail.getNext();
Node sentinel = tail;
while (walkA != sentinel) {
if (!(walkA.getElement().equals(walkB.getElement())))
return false;
walkA = walkA.getNext();
walkB = walkB.getNext();
}
return true;
}
但是现在我将为此类而不是Object.equals方法调用equals方法吗?
好的,所以我相信我明白了。
public boolean equals(Object o) {
if (o == null)
return false;
if (getClass() != o.getClass())
return false;
CircularlyLinkedList other = (CircularlyLinkedList) o;
if (size != other.size)
return false;
if (tail.equals(other.tail))
return false;
Node walkA = tail.getNext();
Node walkB = other.tail.getNext();
int sizeA = size;
while (sizeA > 0) {
if (!walkA.getElement().equals(walkB.getElement()))
return false;
walkA = walkA.getNext();
walkB = walkB.getNext();
sizeA--;
}
return true;
}
我的测试程序运行正常。
public class TestLinkedLists {
public static void main(String[] args) {
DoublyLinkedList<String> double1 = new DoublyLinkedList<>();
DoublyLinkedList<String> double2 = new DoublyLinkedList<>();
DoublyLinkedList<String> double3 = new DoublyLinkedList<>();
DoublyLinkedList<String> double4 = new DoublyLinkedList<>();
CircularlyLinkedList<String> circ1 = new CircularlyLinkedList<>();
CircularlyLinkedList<String> circ2 = new CircularlyLinkedList<>();
CircularlyLinkedList<String> circ3 = new CircularlyLinkedList<>();
CircularlyLinkedList<String> circ4 = new CircularlyLinkedList<>();
double1.addFirst("asdf");
double1.addFirst("ghjk");
double2.addFirst("asdf");
double2.addFirst("ghjk");
double3.addFirst("asdf");
double3.addFirst("asdf");
double4.addFirst("ghjk");
double4.addFirst("ghjk");
circ1.addFirst("asdf");
circ1.addFirst("ghjk");
circ2.addFirst("asdf");
circ2.addFirst("ghjk");
circ3.addFirst("asdf");
circ3.addFirst("asdf");
circ4.addFirst("ghjk");
circ4.addFirst("ghjk");
System.out.println(double1.equals(double2));
System.out.println(double3.equals(double4));
System.out.println(circ1.equals(circ2));
System.out.println(circ3.equals(circ4));
}
}