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

时间:2013-11-14 22:29:08

标签: object palindrome listiterator

希望我的头衔解释我正在尝试做什么。我创建了一个LinkedList:

private LinkedList<MyVector> list = new LinkedList();

然后我使用我创建的Palindrome类的构造函数添加到列表中:

//creates arrays of doubles inside of MyVector Objects.
public Palindrome(){

    double[] a1 = {3.0, 4.0, 3.0};
    double[] a2 = {3.5, 4.5, 3.5};

    MyVector a = new MyVector(a1);
    MyVector b = new MyVector(a2);
    MyVector c = new MyVector(a1);
    MyVector d = new MyVector(a2);
    MyVector e = new MyVector(a1);
  //adds the MyVector Objects into the LinkedList  
    list.add(a);
    list.add(b);
    list.add(c);
    list.add(d);
    list.add(e);
}

我现在正在创建一个方法,通过“MyVector”对象列表比较两个不同List Iterators的指针:

public boolean isPalindrome(){

     //iterates through LinkedList From Beginning to End  
     ListIterator<MyVector> itr1 = list.listIterator();

     //iterates through LinkedList from End to Beginning
     ListIterator<MyVector> itr2 = list.listIterator(list.size());


     while (itr1.next() == itr2.previous()){
            return true;
        }

    return false;

}

我的问题是,当我在main方法中创建一个新的Palindrome对象,然后检查对象列表是否实际上是回文时,我总是得到一个输出“列表不是回文“(当我专门制作列表中的对象代表我的测试的回文时,如果你看看我的Palindrome构造函数):

Palindrome pal = new Palindrome();

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

    } else {
        System.out.println("It's not a palindrome");
    }

1 个答案:

答案 0 :(得分:0)

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

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;
}