Presentation is loading. Please wait.

Presentation is loading. Please wait.

JCF Collection classes and interfaces

Similar presentations


Presentation on theme: "JCF Collection classes and interfaces"— Presentation transcript:

1 JCF Collection classes and interfaces
Iterators CS-2851 Dr. Mark L. Hornick

2 The Java Collections Framework…
Is implemented as a series of hierarchies with: interfaces at the top abstract classes in the middle and concrete (instantiable) classes at the bottom CS-2851 Dr. Mark L. Hornick

3 A small part of the hierarchy:
CS-2851 Dr. Mark L. Hornick

4 The Collection interface declares methods for inserting, removing and searching for an element in a collection All Collections support the following: add(E element) remove(int index) contains(E element) ... CS-2851 Dr. Mark L. Hornick

5 The List interface extends the Collection interface by supplying some index-oriented methods
List-specific behavior that, for example, doesn’t make sense for all Collections add(int index, E element) get(int index) set(int index) ... Some data structures, like queues, are Collections but not Lists – meaning their elements cannot be accessed by index. CS-2851 Dr. Mark L. Hornick

6 The Collection interface extends the Iterable interface
The Iterable interface declares a single method: iterator(), which returns an Iterator object An Iterator is an object that allows a user to loop through a Collection without accessing the elements directly CS-2851 Dr. Mark L. Hornick

7 Every JCF class that implements Collection can be iterated
Associated with each class that implements the Collection interface, there is a private inner class that implements the Iterator interface CS-2851 Dr. Mark L. Hornick

8 Accessing and using a collection’s Iterator
To get an Iterator from a Collection, use the iterator() method ArrayList<Double> al= new ArrayList<Double)(); // Get an Iterator object to iterate over // this collection. Iterator<Double> itr = al.iterator(); while( itr.hasNext() ) { // while elements exist… double x = itr.next(); // …get the next element System.out.println( x ); } CS-2851 Dr. Mark L. Hornick

9 The Iterator<E> methods
public interface Iterator<E> { // Returns true if this Iterator object is positioned // at an element in the collection. public boolean hasNext(); // Returns the element this Iterator object is // positioned at, and advances this Iterator object. public E next(); // Removes the element returned by the most // recent call to next(). public void remove(); } // interface Iterator CS-2851 Dr. Mark L. Hornick

10 The for-each loop uses a collection’s Iterator automatically
// create a collection List<Double> al = new ArrayList<Double>(); // use the built-in Iterator… for( Double x : al ) // “for each x in al” System.out.println(x); CS-2851 Dr. Mark L. Hornick


Download ppt "JCF Collection classes and interfaces"

Similar presentations


Ads by Google