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.
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.
package com.javapapers.java; import java.util.ArrayList; import java.util.List; public class JavaGenericsExample { public static void main(String args[]) { ListanimalsList = new ArrayList (); animalsList.add("Lion"); animalsList.add("Crocodile"); animalsList.add("Hyena"); for (String animal : animalsList) { System.out.println(animal); } } }
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
public interface Listextends Collection { ... boolean add(E e); ... }
public class ArrayListextends AbstractList implements List , RandomAccess, Cloneable, java.io.Serializable { ... public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } ... }
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.
ListanimalsList = new ArrayList ();
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[]) { ListanimalsList = 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); } }
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 extends String> list) { return list.subList(0, 2); }
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[]) { Cupcup = 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 extends Drink> 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.
Comments are closed for "Java Generics Basics".
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.
I meant List<String<, Comments in the blog not accepting diamonds…
public static List topTwo(List list) {
return list.subList(0, 2);
}
extends String ? is it possible? i’m not able to understand that ?
What is difference between Generic Type & Wildcard Type?
very nice explanation
public static List topTwo(List list) {
return list.subList(0, 2);
}
“List<? extends String" is this possible as string is final?
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 :)
Hi Joe,
It is nice article about Generics and its types. It is good informative and understandable.
Thanks for the information and keep going …!
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);
}
correction in Snippet 2:
public static List topTwo(List list) {
return list.subList(0, 2);
}
[…] 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. […]
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.
@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
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.