Java check if Stack contains certain class

NapoleonTheCake :

I use Stack to store objects of different classes. I want to pop until I meet certain Class. But I do NOT want to pop anything if that stack doesn't contain required Class. I have extended Stack like that:

  private class ClassStack<T> extends Stack<T>
  {
    public boolean containsClass(Class type)
    {
      for (int c = 0; c < size(); c++)
        if (type.isInstance(get(c)))
          return true;
      return false;
    }
  }

But I'm unsure about implementation. First, I'm unsure whether get() for Vector that I use is O(1) or not. Second, I don't know if I should touch those methods. Maybe there is a better way to achieve this? Thank you.

SDJ :

The Javadocs for Stack state:

A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class.

To check that the Deque contains an object of a class or not, you can use a stream operation, which avoids having to use inheritance. An example helper method to do this:

private static boolean contains(Class<?> test, ArrayDeque<?> input) {
    return input.stream()
            .map(Object::getClass)
            .anyMatch(Predicate.isEqual(test));
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=356506&siteId=1
Recommended