我不确定如何解释这一点,但基本上我是想参考列表类前面,它是元素A (可以来自任何列表)。但是,当它通过列表的元素时,它会从两个不同的列表进行比较,最终不匹配。即将包含前b的原始列表与包含元素A的列表进行比较。现在我只是想知道如何将前面的元素A设置为b 以便我可以比较它的位置。
/*front is a dummy element used to keep position.
List is a class i have made under requirements of naming for subject.
i don't want a solution. I only want to know about how to do it.
This is what is an example code of whats causing the problem USED IN DRIVER PROGRAM
DLL.concat(DLL2);
it is basically getting DLL's front and going through the loop when it should be using DLL2's.
DLL and DLL2 are both Lists
***/
//will return the index of the Element for comparing
private int checkElement(Element A){
Element b = front;
int i = 0;
while (b != a && i<size)
{
b = b.next;
i++;
}
return i;
}
//edit: add
//size is the size of the list gets increased everytime a variable is added to the list on top of the dummy element.
//Item is a private class inside the List class. it contains the values: element,next, previous in which element contains an object, next and previous contain the next element in the list and the previous one (its a double linked list)
// this is what causes the error to turn up in the above method as im using two different lists and joining them.
public void concat(List L){
if (splice(L.first(),L.last(),last())){
size = size+L.size;
}
}
//this is the splice method for cutting out elements and attaching them after t
//just using the check method to assert that a<b and will later use it to assert t not inbetween a and b
public boolean splice(Element a, Element b, Element t){
if (checkElement(a) < checkElement(b)){
Element A = a.previous;
Element B = b.next;
A.next = B;
B.previous = A;
Element T = t.next;
b.next = T;
a.previous = t;
t.next = a;
T.previous = b;
return true;
}
else {
System.out.println("Splicing did not occur due to b<a");
return false;
}
}
答案 0 :(得分:1)
所以尽管我发表评论,但我看到了一个明显的问题。您不能在引用类型上使用相等运算符。也就是说,除了原始类型(double,int等)之外的任何东西。你要比较的是实例的地址,除非它们实际上是同一个对象(内存中的相同地址),否则它不会返回true。也许这就是你想要的,但我怀疑不是。您需要覆盖方法
public boolean equals(Object obj);
并使用它来比较给定类的两个实例。我的假设是否正确?
编辑好的,我认为我的原始猜测是正确的。它是有效的,如果它们来自同一个列表,因为它们最终是相同的元素(存储在相同的内存位置)。您需要使用equals()
或!equals()
而不是==
和!=
。试试看,看看它是否解决了你的问题。此外,不要只使用它们,您必须覆盖equals
以实际比较元素内部属性。