Java Reference
In-Depth Information
After creation: Size = 0, Elements = []
After adding 3 elements: Size = 3, Elements = [Ken, Lee, Joe]
After removing 1 element: Size = 2, Elements = [Ken, Joe]
After clearing all elements: Size = 0, Elements = []
Traversing Collections
Most often, you need to access all elements of a collection one at a time. Different types of collections store their
elements differently using different types of data structures. Some collections impose ordering on their elements and
some do not. The Collections Framework provides the following ways to traverse a collection:
Iterator
Using an
Using a for-each loop
forEach() method
Using the
some collections, such as lists, assign each element an index and they let you access their elements using indexes.
You can traverse those collections using a regular for-loop statement as well. You can also traverse collections by converting
them into streams and performing an aggregate operation on those streams. i will discuss streams in Chapter 13.
Tip
Using an Iterator
A collection provides an iterator to iterate over all its elements. Sometimes an iterator is also known as a generator or a
cursor . An iterator lets you perform the following three operations on a collection:
Check if there are elements that have not been yet accessed using this iterator.
Access the next element in the collection.
Remove the last accessed element of the collection.
the meaning of the term “next element” of a collection depends on the collection type. the iterator itself does
not impose any ordering in which it returns the elements from a collection. however, if the collection imposes ordering
on its elements, the iterator will maintain the same ordering. in general, the “next element” means any element in the
collection that has not been returned by this iterator yet.
Tip
An iterator in Java is an instance of the Iterator<E> interface. You can get an iterator for a collection using
the iterator() method the Collection interface. The following snippet of code creates a list of strings and gets an
iterator for the list:
// Create a list of strings
List<String> names = new ArrayList<>();
 
 
Search WWH ::




Custom Search