6

I was trying to solve the advent of code 2021 challenge day 10 in Kotlin when I needed to use a stack. After finding out that you shouldnt use Stack anymore but ArrayDeque instead I got provided with two options: java.util.ArrayDeque and kotlin.collections.ArrayDeque. I tried out both but only the Java one acted like intended (stack.push(), stack.pop(), etc). The Kotlin one does not provide those methods.

So I was wondering which one I should use in which case.

1
  • 3
    "The Kotlin one does not provide those methods." -- Sure it does, it just doesn't call them by those names. addFirst and removeFirst add and remove elements from the head of the Deque just fine. Commented Dec 30, 2021 at 23:18

1 Answer 1

5

Kotlin methods that resemble the required operations are

  1. Stack.push = addLast()
  2. Stack.pop = removeLast()
Sign up to request clarification or add additional context in comments.

5 Comments

Alright, I get that the method names are different but why are those two different in first place?
@René In java, ArrayDeque inherits these methods from Deque. But Kotlin, the corresponding methods are available only in ArrayDeque (it inherits only List specific methods). I don't have much knowledge on the reasons for this name choice. Happy New Year :)
The Java class also defines the addLast, etc. names. And in my mind, those are less ambiguous, to be fair. Once you have a two-sided container, the push/pop/enqueue/dequeue/shift/unshift/etc metaphors start to get confusing. A clear-cut addLast and removeLast makes it quite plain and obvious which side is being interacted with.
If you look at the docs for the Deque interface (docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/…) you'll see they refer to e.g. pop() as the Stack method, and removeFirst() as the equivalent Deque method. So at a guess, the Stack methods are included for backwards compatibility because Deque is meant to be used as a drop-in replacement - but the "real" methods are the Deque ones, which are mirrored in the Kotlin implementation. Kotlin doesn't bother with the "pretend it's a stack" methods - it's a queue and you can just use one end of it!
You actually only need a MutableList to be able to call add() and removeLast() for the stack functionality. ArrayDeque is useful when you need a queue, O(1) complexity to add or remove at both start and end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.