Studyon Minte9.com
Head First (Java)




Generics



Generics is to let you write type-safe collections. In other words, code that makes the compiler stop you 
from putting a Dog into a list of Ducks.

* Without generics
	
	There will be no error even if you are putting Strings in a list of songs!

	%java
		package testingapp;
		import java.util.*;

		public class TestingApp {

		    public static void main(String[] args) {
			
			ArrayList listOfSongs = new ArrayList();
			list1.add("a");
			list1.add(new Song("my song"));
			System.out.println(list1);
			    // Output:
			    // [a, my song]
		    }
		    
		    static class Song {
			String title;
			
			Song (String t) {
			    title = t;
			}
			
			public String toString() {
			    return title;
			}
		    }
		}


* With generics

	You don't need to worry about someone sticking a String where it must be a Song

	%java
		package testingapp;
		import java.util.*;

		public class TestingApp {

		    public static void main(String[] args) {
			
			ArrayList<Song> listOfSongs = new ArrayList<Song>();

			/*--- Look here---*/

			listOfSongs.add("a"); // Compiler error at this line

			listOfSongs.add(new Song("my song"));
			System.out.println(listOfSongs);
		    }
		    
		    static class Song {
			String title;
			
			Song (String t) {
			    title = t;
			}
			
			public String toString() {
			    return title;
			}
		    }
		}


* ArrayList Documentation

	Since ArrayList is our most-used generified type, we'll look at its documentation.

	THIS code:

		ArrayList<String> list = new ArraList<String>();

	MEANS:
		public class ArrayList<E> extends AbstractList<E> ... {
			
			public boolean add(E o) {
				// more code
			}
		}
	
	COMPILE like:
		public class ArrayList<String> extends AbstractList<String> ... {
			
			public boolean add(E o) {
				// more code
			}
		}

	In other words, the "E" is replaced by the realtype (also called the type parameter) that you use when 
	you create the ArrayList. That's why the add() method won't let you add anything except objects of a 
	reference type that's compatible with the type of "E".

	<T> or <E>

	The convention is to use a single letter, and a further convention is to use "T" unless you're specifically 
	writing a collection class where you'd us "E" to represent the type of the Element the collection will 
	hold.