From : http://java.boot.by/scjp-tiger/

Write code that uses the generic versions of the Collections API, in particular, the Set<E>, List<E>, Queue<E> and Map <K,V> interfaces and implementation classes. Recognize the limitations of the non-generic Collections API and how to refactor code to use the generic versions.

When you take an element out of a Collection, you must cast it to the type of element that is stored in the collection. Besides being inconvenient, this is unsafe. The compiler does not check that your cast is the same as the collection's type, so the cast can fail at run time.

Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection.

Without generics:

static void expurgate(Collection c) {
	for (Iterator i = c.iterator(); i.hasNext(); ) {
		if (((String) i.next()).length() == 4) {
			i.remove();
		}
	}
}
					

Here is the same example modified to use generics:

					
static void expurgate(Collection<String> c) {
	for (Iterator<String> i = c.iterator(); i.hasNext(); ) {
		if (i.next().length() == 4) {
			i.remove();
		}
	}
}

					

When you see the code <Type>, read it as "of Type"; the declaration above reads as "Collection of String c". The code using generics is clearer and safer. We have eliminated an unsafe cast and a number of extra parentheses. The compiler can verify at compile time that the type constraints are not violated at run time. Because the program compiles without warnings, we can state with certainty that it will not throw a ClassCastException at run time. The net effect of using generics, especially in large programs, is improved readability and robustness.

public interface Queue<E> extends Collection<E>

A collection designed for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, extraction, and inspection operations.

Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner. Among the exceptions are priority queues, which order elements according to a supplied comparator, or the elements' natural ordering, and LIFO queues (or stacks) which order the elements LIFO (last-in-first-out). Whatever the ordering used, the head of the queue is that element which would be removed by a call to remove() or poll(). In a FIFO queue, all new elements are inserted at the tail of the queue. Other kinds of queues may use different placement rules. Every Queue implementation must specify its ordering properties.

The offer method inserts an element if possible, otherwise returning false. This differs from the Collection.add method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity (or "bounded") queues.

The remove() and poll() methods remove and return the head of the queue. Exactly which element is removed from the queue is a function of the queue's ordering policy, which differs from implementation to implementation. The remove() and poll() methods differ only in their behavior when the queue is empty: the remove() method throws an exception, while the poll() method returns null.

The element() and peek() methods return, but do not remove, the head of the queue.

The Queue interface does not define the blocking queue methods, which are common in concurrent programming. These methods, which wait for elements to appear or for space to become available, are defined in the BlockingQueue interface, which extends this interface.

Queue implementations generally do not allow insertion of null elements, although some implementations, such as LinkedList, do not prohibit insertion of null. Even in the implementations that permit it, null should not be inserted into a Queue, as null is also used as a special return value by the poll method to indicate that the queue contains no elements.

Queue implementations generally do not define element-based versions of methods equals and hashCode but instead inherit the identity based versions from class Object, because element-based equality is not always well-defined for queues with the same elements but different ordering properties.

public boolean offer(E element)

public E remove()      // removes !
public E poll()        // removes !

public E element()     // DOES NOT remove !
public E peek()        // DOES NOT remove !
					

PriorityQueue<E>

An unbounded priority queue based on a priority heap. This queue orders elements according to an order specified at construction time, which is specified either according to their natural order (see Comparable), or according to a Comparator, depending on which constructor is used. A priority queue DOES NOT permit null elements. A priority queue relying on natural ordering also DOES NOT permit insertion of non-comparable objects (doing so may result in ClassCastException).

NOTE, java.lang.String implements Comparable.

The head of this queue is the least element with respect to the specified ordering. If multiple elements are tied for least value, the head is one of those elements - ties are broken arbitrarily. The queue retrieval operations poll, remove, peek, and element access the element at the head of the queue.

Example:

PriorityQueue queue = new PriorityQueue();
queue.offer("CCC-1");
queue.offer("BBB");
queue.offer("AAA");
queue.offer("CCC-2");
		
out.println("1. " + queue.poll()); // removes
out.println("2. " + queue.poll()); // removes
out.println("3. " + queue.peek());
out.println("4. " + queue.peek());
out.println("5. " + queue.remove()); // removes
out.println("6. " + queue.remove()); // removes
out.println("7. " + queue.peek());
out.println("8. " + queue.element()); // Throws NoSuchElementException !
					
The output will be:
1. AAA
2. BBB
3. CCC-1
4. CCC-1
5. CCC-1
6. CCC-2
7. null
Exception in thread "main" java.util.NoSuchElementException
	at java.util.AbstractQueue.element(Unknown Source)
	at regex.Replacement.main(Replacement.java:28)
					

Non-generic collections

Example of using raw (non-parameterized) collections with generics (parameterized) collections:


ArrayList list = new ArrayList(); // OK 
ArrayList<String> listStr = list; // WARNING, but OK
ArrayList<StringBuffer> listBuf = list; // WARNING, but OK
listStr.add(0, "Hello"); // OK
StringBuffer buff = listBuf.get(0); // Runtime Exception !
					
					
Exception in thread "main" java.lang.ClassCastException: java.lang.String
	at Client.main(Client1.java:28)