Scala Stack apply()方法示例

Scala Stack apply()方法示例

Scala Stack类中, apply() 方法用于返回堆栈中给定位置的元素。堆栈的顶部对应于位于0 th位置的元素,依此类推。

方法定义:def apply(idx:Int):A

返回类型:它返回堆栈中给定位置的元素。

示例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 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程