Search code examples
javastackarraydeque

Java: How to tell if Two ArrayDeque are equal?


Is there a way to tell if Two Array Deques are equal in Java? Stack has an .equals() operator?

What is data values equals method for Array Deque? this is what I wrote temporarily, however it removes items from the Deque. If there is no library method, any way to optimize code below?

ArrayDeque<Character> sQueue = new ArrayDeque<Character>();
ArrayDeque<Character> tQueue = new ArrayDeque<Character>();

if (sQueue.size() != tQueue.size()) return false;

while (!sQueue.isEmpty()) {
   if (sQueue.removeLast() != tQueue.removeLast()) {
       return false;
   }
}

return true;

Question Context: for people who use Leetcode Backspace String Compare

Also, is the original Equals for ArrayDeque just checking thememory pointer variable? this does not seem to work.

enter image description here

Resource: Why doesn't ArrayDeque override equals() and hashCode()?


Solution

  • Your code probably would work if you don't use != but instead this:

        if (!Objects.equals(sQueue.removeLast(), tQueue.removeLast())) {
    

    There's one issue with your code - it removes all contents of the queue. To prevent that, besides using toArray() as suggested in one of the comments, you an use an Iterator; Deque mandates that it returns "the elements in this deque in proper sequence":

    ArrayDeque<Character> sQueue = new ArrayDeque<Character>();
    ArrayDeque<Character> tQueue = new ArrayDeque<Character>();
    
    // shortcut - that's fine
    if (sQueue.size() != tQueue.size()) return false;
    
    Iterator<Character> sIterator = sQueue.iterator();
    Iterator<Character> tIterator = sQueue.iterator();
    
    while (sIterator.hasNext()) {
        // tIterator.hasNext() will also be true
        if (!Objects.equals(sIterator.next(), tIterator.next())) {
            return false;
        }
    }
    // sIterator and tIterator are both exhausted so all elements are equal
    return true;
    

    You can do it without the length check, by making two changes:

    1. Replace while (sIterator.hasNext()) { with while (sIterator.hasNext() && tIterator.hasNext()) { - keep looping until at least one of the iterators is exhausted.
    2. Replace the final return true; with return sIterator.hasNext() == tIterator.hasNext(); - return true only if both iterators are exhausted.