Search code examples
javadata-structurescollectionsqueuedeque

How can I find-and-return an object in a Dequeue?


I'm using a double-ended queue (java.util.Dequeue) and want to find an object in the queue and return it.

I'm currently using the contains() method to check if the queue contains the object, but don't know how to get the actual instance of the object found. The instance being searched is not the same instance, as I'm overriding the equals() method to test equality of a subset of class variables.

If it's not possible to do this using a Dequeue then what should I use instead? I need to push objects onto either end of a list and remove them from the start. And obviously be able to search for an object and get its instantiation.


Solution

  • Its a little unclear to me if you wish to remove remove the object you are searching for, but, one possible solution is to get a iterator and, well, iterate though the list and manually do the equality check.

    Iterator<YourClass> it = yourDeque.iterator();
    YourClass foundInstance = null;
    while(it.hasNext()) {
        YourClass obj = it.next();
        if(obj.equal(theInstanceYouAreSearchingFor)) {
            foundInstance = obj;
            break;
        }
    }
    if(foundInstance != null) {
       yourDeque.remove(foundInstance); // if you wish to remove it as well
    }