Generics
Examples
What is Generics
• Collections can store Objects of any Type
• Generics restricts the Objects to be put in a
collection
• Generics ease identification of runtime errors
at compile time
Consider this code snippet
List v = new ArrayList();
[Link](new String("test"));
Integer i = (Integer) [Link](0);
Consider this code snippet
List v = new ArrayList();
[Link](new String("test"));
Integer i = (Integer)[Link](0); // Runtime error .
Cannot cast from String to Integer
This error comes up only when we are executing
the program and not during compile time.
Use Generics to eliminate the
Runtime error
How does Generics help
The previous snippet with Generics is
List<String> v = new ArrayList<String>();
[Link](new String("test"));
Integer i = [Link](0); // Compile time error. Converting String to
Integer
Wildcards
• Wildcards help in allowing more than one type
of class in the Collections
• We come across setting an upperbound and
lowerbound for the Types which can be
allowed in the collection
• The bounds are identified using a ? Operator
which means ‘an unknown type’
Upperbound
• List<? extends Number> means that the given list
contains objects of some unknown type which
extends the Number class
Consider the snippet
List<Integer> ints = new ArrayList<Integer>();
[Link](2);
What if we want a List which allows us to put all Number Class
objects
Upperbound
List<? extends Number> nums = ints;
[Link](3.14);
Integer x = [Link](1);
Example 1
• Give code to iterate (using an iterator) across a
List x containing Strings
• All the Strings in x should be appended to a
String named answer
Example 1
String answer = "";
for (Iterator<String> i = [Link](); [Link]();)
answer += [Link]();
Raw Type is Unsafe: Use Generics to
make the following code safe
// [Link]: Find a maximum object
public class Max {
/** Return the maximum between two objects */
public static Comparable max(Comparable o1, Comparable o2) {
if ([Link](o2) > 0)
return o1;
else
return o2;
}
}
Runtime Error:
[Link]("Welcome", 23);
12
Make it Safe
// [Link]: Find a maximum object
public class Max1 {
/** Return the maximum between two objects */
public static <E extends Comparable<E>> E max(E o1, E o2) {
if ([Link](o2) > 0)
return o1;
else
return o2;
}
}
[Link]("Welcome", 23);
13
Generics with subclass
• Consider a method that takes some collection
of Shapes as a parameter, and returns the sum of all
the areas.
• public double areaOfCollection
(Collection<Shape> c)
{ double sum = 0.0;
for (Shape s : c)
sum += [Link]();
}
14
Generics with subclass
• What if we want to use any subclass of Shape class?
• Collection<Shape> or Collection<Circle>
• ( Circle is a subclass of shape), Verify if the given
method works if we call it with a Collection<Circle>
object.
15
Generics with subclass
public double areaOfCollection (Collection<? extends Shape> c)
{
double sum = 0.0;
for (Shape s : c)
sum += [Link]();
}
16