Page 1 of 1

Intro Generics Quick introduction to generics Rate Topic: -----

#1 tivrfoa  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 9
  • View blog
  • Posts: 98
  • Joined: 25-January 09

Post icon  Posted 27 October 2009 - 09:37 PM

This tutorial shows some uses of generics.

Generics and Collections

A non-generic collection can hold any kind of object. Hence, the methods that get objects out of the collection are of the type java.lang.Object.

Suppose you intend to have a list of String’s objects.
Without generics:
List l = new ArrayList();
l.add(10); // It compiles fine *

// Getting the length of all strings in this list
Iterator i = l.iterator();
while(i.hasNext()) {
	String s = (String); // cast is needed

* Pay attention here. I said that compiles fine, but this is true only for Java 5 or above. Java 5 introduced the autoboxing and unboxing features. What the code really does is to insert an Integer object which has the value 10.

This code runs fine, until it tries to cast an Integer to String. So an exception is through at runtime:
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

Two great things about generics are that it ensures the type of objects that the collection can have and also eliminates the need to cast. The problem with cast is that it can fails at runtime time. Using generics, this error is caught at compile time.

Now the same code using generics:
// With generics
List<String> l = new ArrayList<String>();
/*l.add(10); /* It won't compile.
		Error: generics\ cannot find symbol
		symbol  : method add(int)
		location: interface java.util.List<java.lang.String>
			l.add(10); // Won't compile. Error:

// Getting the length of all strings in this list
for(String s:l) {

Remove the “/*” before l.add(10); to generate the compile error.

You can easily use generics for parameter and return types. The following examples illustrate this.

public List<String> getList() {
	return new ArrayList<String>();

public void setList(List<String> list) {
	myList = list;

Ok. Those were the basic uses of generics. Let’s see other interesting things.

Legacy Code

The following code will compile:

List<String> l2 = new ArrayList<String>();
OldClass oc = new OldClass();
oc.insert(l2); // No compile error and no exception
for(String s:l2) { // ClassCastException

class OldClass {
	public void insert(List list) {
		list.add(new Integer(10));

In order to support legacy code, Java 5 and Java 6 allows your newer type safe code to make use of older code. So code above compiles, even passing an Integer object to a list of String. The exception only happens when you try to cast from Integer to String.


Polymorphism doesn’t apply for generics.
class Animal {}
class Dog extends Animal {}
List<Animal> list = new ArrayList<Dog>();

incompatible types
found : java.util.ArrayList<generics.Dog>
required: java.util.List<generics.Animal>
List<Animal> pList = new ArrayList<Dog>();

So, in the below method, the only thing you can pass as parameter is List<Animal>.
public void add(List<Animal> animals) {}
List<Dog> dogs = new ArrayList<Dog>();
add(dogs); // error

? wildcard

You can use the wildcard “?” to partially solve the above problem.
public void add(List<? extends Animal> animals) {}
List<Dog> dogs = new ArrayList<Dog>();
add(dogs); // OK!! :)

But you can’t really add something to the list, not even an Animal.
public void add(List<? extends Animal> animals) {
animals.add(new Animal()); // very awkward error :(

The extends keyword can also be used with interfaces (in this case!).
public void add(List<? extends Runnable> list) {}

Another Java keyword has a special meaning in generics: super.
public void add(List<? super Dog> dogs) {
	dogs.add(new Dog());

It means that you can pass a Dog or a supertype of Dog. Note that you can only add a Dog!


This was a simple introduction. I recommend you to make a search to learn some tricks and advanced techniques.

Sierra, Katherine; Bates, Bert. SCJP Sun Certified Programmer for Java 6.
It’s an AMZING BOOK!!!

Is This A Good Question/Topic? 3
  • +

Page 1 of 1