Transcript Generics9

Generics
Chapter 21
Liang, Introduction to Java Programming
1
Place these programs and their classes from folder Generics on the
desktop
GenericMethodDemo
GenericClass.java
GenericClass2.java
Liang, Introduction to Java Programming
2
Objectives
 To
use generic classes and interfaces from the
API
 To
declare generic classes and interfaces
 To
understand why generic types can improve
reliability and robustness
 To
declare and use generic methods
 To
know wildcard types and understand why
they are necessary
Liang, Introduction to Java Programming
3
Introduction
Generic
is the capability to
parameterize types
You
can declare a generic type in
class, interface, or method
a
You
can specify a concrete type when
using the generic class, interface or
methods

Generic types can improve readability, reliability and
robustness for the program

The new JDK 1.5 generic types provide a mechanism
4
Liang,
Introduction to Java
that supports type
checking
at Programming
compile time
Generic Type
package java.lang;
package java.lang;
public interface Comaprable {
public int compareTo(Object o)
}
public interface Comaprable<T> {
public int compareTo(T o)
}
(b) JDK 1.5
(a) Prior to JDK 1.5
Runtime error
Generic Instantiation
Comparable c = new Date();
System.out.println(c.compareTo("red"));
Comparable<Date> c = new Date();
System.out.println(c.compareTo("red"));
(a) Prior to JDK 1.5
b) Improves reliability
Liang, Introduction to Java Programming
(b) JDK 1.5
Compile error
5
Generics contd.
The prior slide declares that c is a reference variable whose
type is Comparable<Date> in JDK 1.5 and invokes the
compareTo method to compare a Date object with a string.
The code has a compile error, because the argument passed to
the compareTo method must be of the Date type.
Since the errors can be detected at compile time rather than at
runtime. The generic type makes the program more reliable.
Liang, Introduction to Java Programming
6
Generics contd.
Caution: Generic type must be reference types. You cannot
substitute a generic type with a primitive such as int, double,
or char, float, etc.
However, you can use wrapper classes such as Integer,
Double, Character, etc instead.
Note: Occasionally , a generic class may have more than one
parameter. In this case, place the parameters together inside
the angle brackets, separated by commas such as <E1, E2,
E3>
Liang, Introduction to Java Programming
7
The ArrayList Class in JDK1.5 is now a Generic class
Java.util.ArrayList<E>
+ArrayList()
+add(E o): boolean
+add(int index, E element) : void
+clear() : void
+clone() : Object
+get(int index) : E
+indexOf(Object elem) : int
+set(int index, E element) : E
Liang, Introduction to Java Programming
8
ArrayList
The ArrayList class is a generic class. You can form array lists that
collect different types, such as ArrayList<String>,
ArrayList<Customers> and so on
Liang, Introduction to Java Programming
9
Create an ArrayList

Create a list for a String
ArrayList<String> list = new ArrayList<String>();

Add only strings to the list
list.add(“red”);

The following statement will generate an error
list.add(new Integer(1));
because list can only contain strings
Liang, Introduction to Java Programming
10
No Casting Needed
Casting is not needed to retrieve a value from a list with a specified
element type because the compilier already knows the element type:
ArrayList<Double> list = new ArrayList<Double>();
list.add(5.5); // 5.5 is automatically converted to new Double(5.5)
list.add(3.0); // 3.0 is automatically converted to new Double(3.0)
Double doubleObject = list.get(0); // No casting is needed
double d = list.get(1); // Automatically converted to double
Liang, Introduction to Java Programming
11
Implementing Generic Classes
We need to give names to the type variables. It is consider good form
to give short uppercase names for type variables, such as the
following:
Type Variable Name
Meaning
E
Element type in a collection
K
Key type in a map
V
Value type in a map
T
General type
S,U
Additional general types
Liang, Introduction to Java Programming
12
Syntax for Defining a Generic Class
accessSpecifier class GenericClassName <TypeVariable1,
TypeVariable2,…>
{
constructors
methods
fields
}
Liang, Introduction to Java Programming
13
Creating a Generic Class
public class GenericClass<E>
{
private E[] element; //an array to store elements
private int size;
//default constructor
public GenericClass()
{
element = (E[]) new Object[10];//set physical size of 10
size = 0;
}
Liang, Introduction to Java Programming
14
Important Facts
It is important to note that a generic class is
shared by all its instances (objects) regardless
of its actual generic type.
GenericStack<String> stack1 = new GenericStack<String> ();
GenericStack<Integer> stack2 = new GenericStack<Integer> ();
Although GenericStack<String> and
GenericStack<Integer> are two types, but there is
only one class GenericStack loaded into the JVM.
Liang, Introduction to Java Programming
15
Generic methods
public static <E> void print (E[] list) {
for (int i =0; i < list.length; i++)
System.out.print(list[i] + " ");
System.out.println();
}
In main:
Integer[] integers = {1, 2, 3, 4, 5};
String[] strings = {"London", "Paris", "New York" };
ClassName.<Integer>print(integers);
ClassName.<String>print(strings);
Liang, Introduction to Java Programming
16
Example
 Run
the program : GenericClass.java
Liang, Introduction to Java Programming
17
Wild Card
To
create a generic method , a wild
card must be used
The wild card argument is
specified by the ?
The wild card specify the unknown
type
Run program GenericClass2.java
Liang, Introduction to Java Programming
18