迭代器
package test_28 object Test { def main(args: Array[String]): Unit = { val list1 = List(1,2,3,4,5) //任务: 输出每一个元素 //list1.foreach(println) //任务: 跳过前两个,从第3个开始输出 //迭代器 //1. 创建一个迭代器(iterator) val it1 = list1.iterator val in2 = it1.drop(2) //2.依次访问每个元素 while (it1.hasNext){ println(in2.next()) } println(in2.hasNext) val list2 = List(1,2,3) val it3 = list2.iterator it3.next() it3.next() it3.next() it3.next() } }
结果是:
3
4
5
false
Exception in thread "main" java.util.NoSuchElementException: head of empty list
at scala.collection.immutable.Nil$.head(List.scala:663)
at scala.collection.immutable.Nil$.head(List.scala:662)
at scala.collection.StrictOptimizedLinearSeqOps$$anon$1.next(LinearSeq.scala:267)
at test_28.Test$.main(Test.scala:27)
at test_28.Test.main(Test.scala)
进程已结束,退出代码1
原文地址:https://blog.csdn.net/wjwjssjjs/article/details/143857154
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!