Java Iterators - Colorado State University
Java Iterators
Motivation
n We often want to access every item in a collection of items
q We call this traversing or iterating q Example: array
for (int i = 0; i < array.length; i++) /* do something with array[i] */
q Easy because we know exactly how an array works!
Motivation
n What if we want to traverse an arbitrary collection of objects?
q Its underlying implementation may not be known to us
n Java provides an interface for stepping through all elements in any collection, called an iterator
Iterating through an ArrayList
n Iterating through an ArrayList of Strings:
for (int i = 0; i < list.size(); i++) {! String s = list.get(i); ! //do something with s!
}!
n Alternative:
Iterator itr = list.iterator();! while (itr.hasNext()) {!
String s = list.next();! }!
This syntax of iteration is generic and applies to any Java class that implements the Iterator interface.
! ! !
Iterating through an ArrayList
n Iterating through an ArrayList of Strings:
for (int i = 0; i < list.size(); i++) {! String s = list.get(i); ! //do something with s!
}!
n Alternative:
Iterator itr = list.iterator();! while (itr.hasNext()) {!
String s = list.next();! }!
Advantage of the alternative: the code will work even if we decide to store the data in a different data structure (as long as it provides an iterator)
! !
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related download
- cs106a stanford handout 49 fall 2004 05 nick parlante
- chapter 19 java data structures
- ch7 list and iterator adts
- arrays and arraylists
- big o arraylist carnegie mellon university
- arrays stanford university
- arraylist reading 10
- arraylist in java
- java arraylist copyright © tutorialspoint
- building java programs chapter 10
Related searches
- colorado state university calendar
- colorado state university calendar 2019 2020
- colorado state university single audit
- colorado state university cost breakdown
- colorado state university tuition fee
- colorado state university tuition 2020
- colorado state university tuition cost
- colorado state university price
- colorado state university tuition 2021
- colorado state university aar
- colorado state university career fair
- colorado state university 2019 schedule