简体   繁体   English

将原始对象与堆栈/队列进行比较-覆盖equals()方法

[英]Comparing raw object with a Stack/Queue - Overriding equals() method

I've created a class which can be inherited to create both a Stack and a Queue using LinkedLists, I've passed all the JUnit tests except the equals one, I still have no idea why it doesn't work. 我已经创建了一个类,可以使用LinkedLists继承该类以创建Stack和Queue,我已经通过了所有JUnit测试(除等号外),我仍然不知道为什么它不起作用。

@Override public boolean equals(Object o) {

    if( o == null) return false;
    if(o == this) return true;


    if(!(o instanceof PushPop)) return false;
    PushPop test1= this;
    PushPop test = (PushPop)o;
    while(!test.isEmpty() && !test1.isEmpty()){
        if(test1.pop() != test.pop()) return false;
    }
    return true;
}

The test sends out an assertion error whenever it's comparing the values, specifically whenever a stack/queue has an extra value than the second one. 每当比较值时,测试都会发出断言错误,特别是当堆栈/队列的值比第二个值大时。

OK, I have located your problem: 好的,我找到了您的问题:

In your test, you do the following [taken from comment] 在测试中,您需要执行以下操作[摘自评论]

stack.push(i);
Assert.assertFalse(stack.equals(stack2));
stack2.push(i);
Assert.assertTrue(stack.equals(stack2));

This seems reasonable. 这似乎是合理的。 However, equals clears both stacks so when you push i onto stack2 , it is no longer equal to the now-empty stack . 但是, equals清除两个堆栈,因此当您push i push stack2 ,它不再等于现在为空的stack

Hence your error. 因此,您的错误。

The solution: Don't Modify Your Object In An equals Method. 解决方案: 不要用equals方法修改对象。

I'd suggest cloning or comparing whatever your underlying data structure is (eg, if you're using Nodes, having Node implement equals ). 我建议克隆或比较您的基础数据结构(例如,如果您使用的是Node,则Node实现equals )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM