基本介绍
元组也可以理解为一个容器,可以存放可以各种相同或不同的数据。说的简单点,就是将多个无关的数据封装为一个整体
元组中最大最大只能有22个元素
元组的创建
1 2 3 4 5
|
val tuple=(1,2,3,"hello",4)
|
元组的访问
基本介绍
访问元组中的数据,可以采用顺序号( _下划线 ) 还可以通过索引(productElement)访问
1 2 3 4 5 6 7 8 9 10
| object TupleDemo { def main(args: Array[String]): Unit = { val tuple = (1, 2, 3, "hello", 4) println(tuple) println(tuple._1) println(tuple.productElement(0)) } }
|
元组的遍历
tuple是一个整体,遍历需要调其迭代器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| object TupleDemo { def main(args: Array[String]): Unit = { val tuple = (1, 2, 3, "hello", 4) println(tuple) println(tuple._1) println(tuple.productElement(0))
for (item <- tuple.productIterator) { println(item) } } }
|