基本介绍

元组也可以理解为一个容器,可以存放可以各种相同或不同的数据。说的简单点,就是将多个无关的数据封装为一个整体

元组中最大最大只能有22个元素

元组的创建

1
2
3
4
5
// 创建tuple
// 说明 tuple就是一个tuple类型是tuple5
// 简单说明,为了更高效的操作元组,编译器根据元组的个数不同,对应不同的元组类型
// 分别是 tuple1 -> tuple22
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)
}
}
}