个性化阅读
专注于IT技术分析

Scala Vector用法示例

本文概述

向量是一种通用的, 不变的数据结构。它提供元素的随机访问。它适合大量元素的收集。

它扩展了抽象类AbstractSeq和IndexedSeq特质。


Scala矢量示例

import scala.collection.immutable._
object MainObject{
    def main(args:Array[String]){
        var vector:Vector[Int] = Vector(5, 8, 3, 6, 9, 4) //Or
        var vector2 = Vector(5, 2, 6, 3)
        var vector3 = Vector.empty
        println(vector)
        println(vector2)
        println(vector3)
    }
}

输出

Vector(5, 8, 3, 6, 9, 4)
Vector(5, 2, 6, 3)
Vector(

Scala矢量示例

在下面的示例中, 我们创建了一个向量。你还可以添加新元素并合并两个向量。

import scala.collection.immutable._
object MainObject{
    def main(args:Array[String]){
        var vector = Vector("Hocky", "Cricket", "Golf")
        var vector2 = Vector("Swimming")
        print("Vector Elements: ")
        vector.foreach((element:String) => print(element+" "))
        var newVector  = vector :+ "Racing" 							// Adding a new element into vector
        print("\nVector Elements after adding: ")
        newVector.foreach((element:String) => print(element+" "))
        var mergeTwoVector = newVector ++ vector2   					// Merging two vector
        print("\nVector Elements after merging: ")
        mergeTwoVector.foreach((element:String) => print(element+" "))
        var reverse = mergeTwoVector.reverse       	 					// Reversing vector elements
        print("\nVector Elements after reversing: ")
        reverse.foreach((element:String) => print(element+" "))
        var sortedVector = mergeTwoVector.sorted    					// Sorting vector elements
        print("\nVector Elements after sorting: ")
        sortedVector.foreach((element:String) => print(element+" "))
    }
}

输出

Vector Elements: Hocky Cricket Golf 
Vector Elements after adding: Hocky Cricket Golf Racing 
Vector Elements after merging: Hocky Cricket Golf Racing Swimming 
Vector Elements after reversing: Swimming Racing Golf Cricket Hocky 
Vector Elements after sorting: Cricket Golf Hocky Racing Swimming
赞(0)
未经允许不得转载:srcmini » Scala Vector用法示例

评论 抢沙发

评论前必须登录!