Object 回文程序帮助:包含双精度数组的对象链接列表。

Object 回文程序帮助:包含双精度数组的对象链接列表。,object,palindrome,listiterator,Object,Palindrome,Listiterator,希望我的标题能解释我想做什么。我已经创建了一个LinkedList: private LinkedList<MyVector> list = new LinkedList(); 我现在创建一个方法,通过“MyVector”对象列表比较两个不同列表迭代器的指针: ==运算符使用对象哈希代码将其与其他对象进行比较,但这些对象不匹配。 通过使用以下代码位可以看到这一点: int hash1 = itr1.next().hashCode(); int hash2 = itr2.previo

希望我的标题能解释我想做什么。我已经创建了一个LinkedList:

private LinkedList<MyVector> list = new LinkedList();
我现在创建一个方法,通过“MyVector”对象列表比较两个不同列表迭代器的指针:


==运算符使用对象哈希代码将其与其他对象进行比较,但这些对象不匹配。 通过使用以下代码位可以看到这一点:

int hash1 = itr1.next().hashCode();
int hash2 = itr2.previous().hashCode();
您需要在MyVector类中重写并使用equals函数,这样才能工作

@Override
public boolean equals(Object other)
{
    boolean retVal = true;
    if(other instanceof MyVector)
    {
        MyVector otherVector = (MyVector) other;
        if(this.x != otherVector.x)
        {
            retVal = false;
        }
        if(this.y != otherVector.y)
        {
            retVal = false;
        }
        if(this.z != otherVector.z)
        {
            retVal = false;
        }
    }
    else
    {
        retVal = false;
    }

    return retVal;
}

谢谢你的回复,我现在明白了为什么我现在得到了输出。由于我正在比较两个迭代器,equals方法的参数不是(ListIterator temp)吗。如果那没有任何意义,我很抱歉。我仍然是所有这些的初学者,因此我很难理解您让我使用的equals方法的功能。下一个\上一个方法会从列表中为您提供一个对象,而不是ListIterator对象。默认的equals方法比较两个对象的哈希代码。我提供的equals函数比较对象的值,而不是其哈希代码。我添加了instanceof操作符,以便在强制转换之前验证该对象是否是MyVector的instance。
Palindrome pal = new Palindrome();

    if(pal.isPalindrome()){
        System.out.println("It's a palindrome");

    } else {
        System.out.println("It's not a palindrome");
    }
int hash1 = itr1.next().hashCode();
int hash2 = itr2.previous().hashCode();
@Override
public boolean equals(Object other)
{
    boolean retVal = true;
    if(other instanceof MyVector)
    {
        MyVector otherVector = (MyVector) other;
        if(this.x != otherVector.x)
        {
            retVal = false;
        }
        if(this.y != otherVector.y)
        {
            retVal = false;
        }
        if(this.z != otherVector.z)
        {
            retVal = false;
        }
    }
    else
    {
        retVal = false;
    }

    return retVal;
}