Iterator
An iterator is an object that
implements the interface java.util.Iterator, it has three
methods hasNext(), next() and remove().
Iterators are used to traverse or
access a collection in a standard way, the java.util.Collection
interface provides the iterator() method so any collection
that implements this interface provides a way to return an iterator.
Example:
Iterator it = collection.iterator() ;
while( it.hasNext() ) {
System.out.println(it.next());
}
Iterable
The java.lang.Iterable interface
was introduced in Java 5, it just has the iterator() method
and
the java.util.Collection interface
extends from this interface. The Iterable interface is used in the
foreach statement in this way, any class that implements the Iterable
interface could be used in the foreach statement.
The advantages of the foreach statement
are that the code needed to traverse a collection is reduced and
that no casts are needed to access the elements of a collection.
Example
for(Object o : collection) {
System.out.println(o);
}
In the example the code looks much more
cleaner than before.
A precaution to take with iterators is
that they are fail-fast, they check collection has not changed. If
they detect a change, a java.util.ConcurrentModificationException
exception is thrown.
This means if a collection is modified
while it is being iterated a ConcurrentModificationException
is thrown.
Generics and collections
Generics were introduced in Java 5,
before that collections could hold any kind of object, there was no
way to guarantee collection type.
Since collections could hold any type
of object, there were no ways to prevente runtime errors such cast
exceptions.
Example:
List list = new ArrayList();
list.add(new Person());
String s = (String) list.get(0);
The example would rise a
ClassCastException.
With generics collections have a way to
do a compile time check by enforcing the type of your collections.
All what it needs is just place the type of the collection between
angle brackets.
Example:
List <String> list = new ArrayList <String> ();
list.add(new Person());//Compiler error
Another advantage is that since the
type is now specified at compile, then the cast for getting an
element could be omitted because now the compiler can check if what
you are doing is correct.
Example:
List <String> list = new ArrayList <String> ();
String s = list.get(0);
Also collection can be iterated in a
for-each statement or with an Iterator with its own type without
doing any cast.
Example:
for (String s : list) {
...
}
.....
Iterator it = collection.iterator() ;
while( it.hasNext() ) {
String s = it.next();
}
There is a wildcard in collections and
generics the “? “ question mark symbol, you have to be
very careful if you used it has many behaviors and restrictions and I
would recommend you to do a further research of it.
If it is used alone in a collection, it
means it can hold any type of object, but you can not add any element
to it, since the compiler doesn't know its exact type.
Example:
List <?> list = new ArrayList <String> ();
list.add(“Hello world”);//compiler error
If it is used with the extends
keyword, it means it can hold any type that extends or implements the
type specified, but still can not add elements to it, since the
compiler doesn't know its exact type.
Example:
List <? extends CharSequence> list = new ArrayList <String> ();//OK
List <? extends CharSequence> list = new ArrayList <StringBuffer> ();//OK
If it is used with the super
keyword, it means it can hold any super type of the type specified,
in this case elements can be added but of the same type or subtype of
the right element in the super expression.
Example:
class Employee extends Person
.......
List <? super Employee> list = new ArrayList <Person> ();
list.add(new Employee);
In the exapmle the class Employee
extends Person, so the list can add any element of type Employee of a
subtype of it.
Java 7 added type inference
which says “You can replace the type arguments required to invoke
the constructor of a generic class with an empty set of type
parameters (<>) as long as the compiler can infer the type
arguments from the context”.
Example
List<String> list = new ArrayList<>();
list.add("A");//OK
As I said before there are many other
restrictions with generics so you better check them, before start
using them.
The java.util.Collection interface
The Collection interface defines the
core functionality of almost every collection, Maps are different.
It defines the following methods:
Adding Elements
boolean add(E e):Ensures that
this collection contains the specified element (optional operation).
boolean addAll(Collection<?
extends E> c): Adds all of the elements in the specified
collection to this collection (optional operation).
Removing Elements
void clear():Removes all of the
elements from this collection (optional operation).
boolean remove(Object o):
Removes a single instance of the specified element from this
collection, if it is present (optional operation).
boolean
removeAll(Collection<?> c): Removes all of this
collection's elements that are also contained in the specified
collection (optional operation).
boolean
retainAll(Collection<?> c): Retains only the elements in
this collection that are contained in the specified collection
(optional operation).
Contents of collection
boolean contains(Object o):
Returns true if this collection contains the specified element.
boolean
containsAll(Collection<?> c): Returns true if this
collection contains all of the elements in the specified collection.
boolean isEmpty():
Returns true if this collection contains no elements.
int size(): Returns the
number of elements in this collection.
Processing contents
Iterator<E> iterator():
Returns an iterator over the elements in this collection.
Object[] toArray(): Returns an
array containing all of the elements in this collection.
<T> T[] toArray(T[] a):
Returns an array containing all of the elements in this collection;
the runtime type of the returned array is that of the specified
array.