100 likes | 253 Views
JCF Collection classes and interfaces. Iterators. 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. A small part of the hierarchy:.
E N D
JCF Collection classes and interfaces Iterators CS-2851 Dr. Mark L. Hornick
The Java Collections Framework… Is implemented as a series of hierarchies with: • interfaces at the top • abstract classes in the middle • and concrete (instantiable) classesat the bottom CS-2851 Dr. Mark L. Hornick
A small part of the hierarchy: CS-2851 Dr. Mark L. Hornick
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
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
The Collection interface extends the Iterableinterface 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
Every JCF class that implements Collection can be iterated Associated with each class that implements the Collection interface, there is a private inner classthat implements the Iterator interface CS-2851 Dr. Mark L. Hornick
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
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
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