Java Generics Basics

This Java generics tutorial is to introduce basic terminologies related to generics. They are demonstrated with example code and this tutorial is for beginners only.

Java Generics Example

Before we go into detail let us see an example for generics in Java. This is to recall and continue from our previous tutorial for introduction to generics. In the following example we are using the generics type implemented for collections. This shows how we can use a generic type.

Java-Generics.jpg

package com.javapapers.java;

import java.util.ArrayList;
import java.util.List;

public class JavaGenericsExample {
	public static void main(String args[]) {
		List animalsList = new ArrayList();
		animalsList.add("Lion");
		animalsList.add("Crocodile");
		animalsList.add("Hyena");

		for (String animal : animalsList) {
			System.out.println(animal);
		}
	}
}

Generic Type

A generic type is the definition of a generic class. The generic type definition will have a placeholder for a type. Following are examples from Java JDK API for generic types

List – JDK Source


public interface List extends Collection {

...
 boolean add(E e);
...

}

ArrayList – JDK Source


public class ArrayList extends AbstractList
        implements List, RandomAccess, Cloneable, java.io.Serializable {

...
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
...

}

Parameterized Type

When a generic type is instantiated, it is called parameterized type. We supply a class/type as parameter for placeholder and create a new object for a generic type. In the above java generics example, we have instantiated a List object by supplying the parameter argument as String.


List animalsList = new ArrayList();

Wildcard Type

Using a generic type with wildcards is wildcard type. In the below example, we have written a new method using generics which uses the wildcard type. We have not give any actual parameter as argument in the topTwo method. We have used a wildcard ? as argument. This states that we can call this method by passing a List containing any type.


package com.javapapers.java;

import java.util.ArrayList;
import java.util.List;

public class GenericsWildcardType {
	public static void main(String args[]) {
		List animalsList = new ArrayList();
		animalsList.add("Lion");
		animalsList.add("Crocodile");
		animalsList.add("Hyena");

		List topTwoAnimals = topTwo(animalsList);

		System.out.println(topTwoAnimals);

	}

	public static List topTwo(List list) {
		return list.subList(0, 2);
	}

}


Bounded Wildcard Type

We can restrict the wildcard type arguments as applicable to only a specific subtype or supertype. Instead of any type at the place of the wildcard ?, it is restricted to the sub or super classes of a specific class. For example, in the above wildcard type example we can add the keyword ‘extends’ as below and restrict it to a subtype only. This is known as upper bound. Similarly ‘super’ can be used to restrict it to a supertype and is known as lower bound.


	public static List topTwo(List list) {
		return list.subList(0, 2);
	}

Generics Custom Type

Following is an example for Java generics demonstrating generic type, parameterized type, wildcard type and bounded wildcard type.


package com.javapapers.java;

/*
 *OUTPUT: 
 Java Generics Rocks: Tea
 Java Generics Poured: Tea

 */

public class CustomGenericType {
	public static void main(String args[]) {
		Cup cup = new Cup();

		Cup cupOfTea = new Cup(new Tea());
		System.out.println("Java Generics Rocks: " + cupOfTea.pour());

		cup.fillFrom(cupOfTea);
		System.out.println("Java Generics Poured: " + cup.pour());
	}
}

class Drink {

	@Override
	public String toString() {
		return "empty";
	}

}

class Tea extends Drink {

	@Override
	public String toString() {
		return "Tea";
	}

}

class Cup {
	String content;

	public Cup() {
	}

	public Cup(E e) {
		content = e.toString();
	}

	public void fillFrom(Cup c) {
		content = c.pour();
	}

	public String pour() {
		return content;
	}
}

This Java generics tutorial you have read now is part two of Generics series and there is lot more to come, keep watching.

This Java tutorial was added on 18/02/2014.

Comments on "Java Generics Basics" Tutorial:

  1. Narendran Solai Sridharan says:

    Nice example code for Wildcard Type, Can We bound it back to List, List topTwoAnimals = topTwo(animalsList);? Is it possible?

    Nice Identification of Tea Cup example. I was still thinking that it would be applicable to data structure mostly, you did change my prespective.

  2. Narendran Solai Sridharan says:

    I meant List&ltString&lt, Comments in the blog not accepting diamonds…

  3. sedhu says:

    public static List topTwo(List list) {
    return list.subList(0, 2);
    }

    extends String ? is it possible? i’m not able to understand that ?

  4. Pushkar says:

    What is difference between Generic Type & Wildcard Type?

  5. suresh kumar bheemini says:

    very nice explanation

  6. Anonymous says:

    public static List topTwo(List list) {
    return list.subList(0, 2);
    }

    “List<? extends String" is this possible as string is final?

  7. Amrit says:

    i like your every blog this is also nice one i love to learn java i already know about generic but it very clear and good example you post

    java rocks :)

  8. Baskar says:

    Hi Joe,

    It is nice article about Generics and its types. It is good informative and understandable.

    Thanks for the information and keep going …!

  9. Anonymous says:

    I understand the use of bounded wildcard types. But it is not clear to me why one would use wild card.
    what is the difference between following code snippets
    snippet 1:
    public static List topTwo(List list) {
    return list.subList(0, 2);
    }

    snippet 2:
    public static List topTwo(List list) {
    return list.subList(0, 2);
    }

  10. Bhaskar says:

    correction in Snippet 2:

    public static List topTwo(List list) {
    return list.subList(0, 2);
    }

  11. […] Before diving into detail it is better for you to go through the fundamentals of cast in Java. This is tutorial is a part of multi-part series on Java generics. Hope you are comfortable on Java generics basics. […]

  12. harkesh kumar says:

    public static List topTwo(List list) {
    list.add(“something”); // it will compile
    return list.subList(0, 2);
    }
    in this we can change the list and know its E type.

    public static List topTwoElements(List list){
    list.add(“something”);//it will not compile
    return list.subList(0, 2);
    }
    in this we can not change and this list is instance of some type but we don’t know the type.

  13. Nagendra says:

    @JOE: I want to know about Wildcard. can you provide the information about it.

    Who introduced?
    Why the name is Wildcard?
    What it means?
    How internally it works?

    Thanks,
    Nagendra

  14. KK says:

    Hi Joe,
    Thanks for the awesome tutorials.
    Btw, I noticed that the tags (used to specify types) are actually not displayed in Google Chrome browser.
    Thanks.

Comments are closed for this "Java Generics Basics" tutorial.