课程: Learning Java Collections

今天就学习课程吧!

今天就开通帐号,24,700 门业界名师课程任您挑!

Accessing collection elements with iterators

Accessing collection elements with iterators - Java教程

课程: Learning Java Collections

Accessing collection elements with iterators

- [Instructor] Let's walk through a few examples involving iterables to see how to traverse a collection. To get us started, I've created a collection of rooms that's backed by an array list implementation. If we want to create an instance of an iterator from this collection, we can declare a variable of type Iterator and give it a generic type of Room. I'll then give it a name and from there we can invoke the iterator method on our collection. This is a factory method that returns a new instance of an iterator. I'm going to use this iterator to print some output to the console. To do that, I'll just invoke the next method on the iterator. Now because the iterator is backed by the collection, we can access collection elements through the next method. Each time we call the next method, it's going to advance one position forward in the collection and return an element. That element is going to be of type Room…

内容