在 Scala Stack class
,則使用apply()方法返回堆棧中給定位置的元素。堆棧的頂部對應於第0位的元素,依此類推。
函數定義: def apply(idx: Int): A
返回類型: It returns an element at a given position in the stack.
範例1:
// Scala program of apply()
// method
import scala.collection.mutable.Stack
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating a stack
val s1 = Stack(1, 2, 3, 4, 5)
// Print the stack
println(s1)
// Applying apply method
val result = s1.apply(0)
// Display output
println("Element at 0th position: " + result)
}
}
輸出:
Stack(1, 2, 3, 4, 5) Element at 0th position: 1
範例2:
// Scala program of apply()
// method
import scala.collection.mutable.Stack
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating a stack
val s1 = Stack("C++", "Java", "Python", "Scala")
// Print the stack
println(s1)
// Applying apply method
val result = s1.apply(2)
// Display output
println("Element at 2nd position: " + result)
}
}
輸出:
Stack(C++, Java, Python, Scala) Element at 2nd position: Python
相關用法
- Scala Map apply()用法及代碼示例
- Scala Set apply()用法及代碼示例
- Scala List apply()用法及代碼示例
- Scala SortedSet apply()用法及代碼示例
- Scala TreeSet apply()用法及代碼示例
- Scala Queue apply()用法及代碼示例
- Scala SortedMap apply()用法及代碼示例
- Scala Listset apply()用法及代碼示例
- Scala Stack contains()用法及代碼示例
注:本文由純淨天空篩選整理自rupesh_rao大神的英文原創作品 Scala Stack apply() method with example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。