📅  最后修改于: 2021-01-09 12:08:41             🧑  作者: Mango
Seq是一个特征,代表可以保证不变的索引序列。您可以使用元素索引来访问元素。它保持元素的插入顺序。
序列支持多种方法来查找元素或子序列的出现。它返回一个列表。
在以下示例中,我们将创建Seq并从Seq访问元素。
import scala.collection.immutable._
object MainObject{
def main(args:Array[String]){
var seq:Seq[Int] = Seq(52,85,1,8,3,2,7)
seq.foreach((element:Int) => print(element+" "))
println("\nAccessing element by using index")
println(seq(2))
}
}
输出:
52 85 1 8 3 2 7
Accessing element by using index
1
您还可以使用反向方法以相反的顺序访问元素。下面我们列出了一些常用的方法及其说明。
Method | Description |
---|---|
def contains[A1 >: A](elem: A1): Boolean | Check whether the given element present in this sequence. |
def copyToArray(xs: Array[A], start: Int, len: Int): Unit | It copies the seq elements to an array. |
def endsWith[B](that: GenSeq[B]): Boolean | It tests whether this sequence ends with the given sequence or not. |
def head: A | It selects the first element of this seq collection. |
def indexOf(elem: A): Int | It finds index of first occurrence of a value in this immutable sequence. |
def isEmpty: Boolean | It tests whether this sequence is empty or not. |
def lastIndexOf(elem: A): Int | It finds index of last occurrence of a value in this immutable sequence. |
def reverse: Seq[A] | It returns new sequence with elements in reversed order. |
在此示例中,我们应用了一些预定义的Seq特征方法。
import scala.collection.immutable._
object MainObject{
def main(args:Array[String]){
var seq:Seq[Int] = Seq(52,85,1,8,3,2,7)
seq.foreach((element:Int) => print(element+" "))
println("\nis Empty: "+seq.isEmpty)
println("Ends with (2,7): "+ seq.endsWith(Seq(2,7)))
println("contains 8: "+ seq.contains(8))
println("last index of 3 : "+seq.lastIndexOf(3))
println("Reverse order of sequence: "+seq.reverse)
}
}
输出:
52 85 1 8 3 2 7
is Empty: false
Ends with (2,7): true
contains 8: true
last index of 3 : 4
Reverse order of sequence: List(7, 2, 3, 8, 1, 85, 52)