BBM 102 – Introduction to
Programming II
Spring 2025
Generics
Today
◼ Create generic methods that perform identical tasks on
arguments of different types.
◼ Understand how to overload generic methods with non-
generic methods or with other generic methods.
◼ Understand raw types and how they help achieve
backwards compatibility.
◼ Use wildcards when precise type information about a
parameter is not required in the method body.
◼ The relationship between generics and inheritance.
2
Introduction
◼ Generics
❑ Provide compile-time type safety
◼ Catch invalid types at compile time
❑ Generic methods
◼ A single method declaration
◼ A set of related methods
❑ Generic classes
◼ A single class declaration
◼ A set of related classes
3
Motivation for Generic Methods
◼ Overloaded methods
❑ Perform similar operations on different types of data
❑ Overloaded printArray methods
◼ Integer array
◼ Double array
◼ Character array
❑ Only reference types can be used with generic
methods and classes
4
1 // Fig. 18.1: [Link]
2 // Using overloaded methods to print array of different types.
3
4 public class OverloadedMethods
5 {
6 // method printArray to print Integer array
7 public static void printArray( Integer[] inputArray )
8 {
9 // display array elements Method printArray accepts
10 for ( Integer element : inputArray ) an array of Integer objects
11 [Link]( "%s ", element );
12
13 [Link]();
14 } // end method printArray
15
16 // method printArray to print Double array
17 public static void printArray( Double[] inputArray )
18 {
19 // display array elements
Method printArray accepts
20 for ( Double element : inputArray ) an array of Double objects
21 [Link]( "%s ", element );
22
23 [Link]();
24 } // end method printArray
25
5
26 // method printArray to print Character array
27 public static void printArray( Character[] inputArray )
28 {
29 // display array elements
Method printArray accepts
30 for ( Character element : inputArray ) an array of Character objects
31 [Link]( "%s ", element );
32
33 [Link]();
34 } // end method printArray
35
36 public static void main( String args[] )
37 {
38 // create arrays of Integer, Double and Character
39 Integer[] integerArray = { 1, 2, 3, 4, 5, 6 };
40 Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
41 Character[] characterArray = { 'H', 'E', 'L', 'L', 'O' };
42
6
43 [Link]( "Array integerArray contains:" );
44 printArray( integerArray ); // pass an Integer array
45 [Link]( "\nArray doubleArray contains:" );
46 printArray( doubleArray ); // pass a Double array
47 [Link]( "\nArray characterArray contains:" );
48 printArray( characterArray ); // pass a Character array
49 } // end main
50 } // end class OverloadedMethods
At compile time, the compiler determines argument
Array integerArray contains: integerArray’s type (i.e., Integer[]), attempts
1 2 3 4 5 6
to locate a method named printArray that
Array doubleArray contains: specifies a single Integer[] parameter (lines 7-14)
1.1 2.2 3.3 4.4 5.5 6.6 7.7
Array characterArray contains:
H E L L O
At compile time, the compiler determines argument
doubleArray’s type (i.e., Double[]), attempts to
locate a method named printArray that specifies
a single Double[] parameter (lines 17-24)
At compile time, the compiler determines argument
characterArray’s type (i.e., Character[]),
attempts to locate a method named printArray that
specifies a single Character[] parameter (lines 7-14)
7
Motivation for Generic Methods (Cont.)
◼ Study each printArray method
❑ Array element type appears in two location
◼ Method header (line 7,17,27)
◼ for statement header (line 10,20,30)
◼ Combine three printArray methods into one
❑ Replace the element types with a generic name E
❑ Declare one printArray method
◼ Display the string representation of the elements of any array
8
1 public static void printArray( E[] inputArray )
2 {
3 // display array elements Replace the element type with
4 for ( E element : inputArray ) a single generic type E
5 [Link]( "%s ", element );
6
7 [Link]();
8 } // end method printArray
Replace the element type with
a single generic type E
9
Generic Methods: Implementation and Compile-
Time Translation
◼ Reimplement using a generic method
❑ Method calls are identical
❑ Outputs are identical
◼ Generic method declaration
❑ Type parameter section
◼ Delimited by angle brackets ( < and > )
◼ Precede the method’s return type
◼ Contain one or more type parameters
❑ Also called formal type paramzters
10
Generic Methods: Implementation and Compile-
Time Translation
◼ Type parameter
❑ Also known as type variable
❑ An identifier that specifies a generic type name
❑ Used to declare return type, parameter types and local
variable types
❑ Act as placeholders for the types of the argument passed to
the generic method
◼ Actual type arguments
❑ Can be declared only once but can appear more than once
public static < E > void printTwoArrays(
E[] array1, E[] array2 )
11
1 // Fig. 18.3: [Link]
2 // Using generic methods to print array of different types.
3
4 public class GenericMethodTest
5 { Use the type parameter to declare
6 // generic method printArray method printArray’s parameter type
7 public static < E > void printArray( E[] inputArray )
8 {
9 // display array elements Type parameter section delimited
10 ) angle brackets (< and > )
for ( E element : inputArray by
11 [Link]( "%s ", element );
12
Use the type parameter to declare method
13 [Link](); printArray’s local variable type
14 } // end method printArray
15
16 public static void main( String args[] )
17 {
18 // create arrays of Integer, Double and Character
19 Integer[] intArray = { 1, 2, 3, 4, 5 };
20 Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
21 Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };
22
12
23 [Link]( "Array integerArray contains:" );
24 printArray( integerArray ); // pass an Integer array
25 [Link]( "\nArray doubleArray contains:" );
26
Invoke generic method printArray
printArray( doubleArray ); // pass a Double array
27 [Link]( "\nArray characterArray an Integer
withcontains:" ); array
28 printArray( characterArray ); // pass a Character array
29 } // end main
Invoke generic method printArray
30 } // end class GenericMethodTest
with a Double array
Array integerArray contains:
1 2 3 4 5 6
Array doubleArray contains:
Invoke generic method printArray
1.1 2.2 3.3 4.4 5.5 6.6 7.7 with a Character array
Array characterArray contains:
H E L L O
13
Good Programming Practice
• It is recommended that type parameters be
specified as individual capital letters.
• Typically, a type parameter that represents
• T (for “type”),
• E (for “element”)(used extensively by the Java Collections Framework)
• K (for “key”) and
• V (for “value”) are commonly used as type
parameters.
14
Generic Methods: Implementation and Compile-
Time Translation
◼ Compile-time translation
❑ Erasure
◼ Remove type parameter section
◼ Replace type parameters with actual types
◼ Default type is Object
15
1 public static void printArray( E[] inputArray )
2 {
3 // display array elements
4 for ( E element : inputArray )
5 [Link]( "%s ", element );
6
7 [Link]();
8 } // end method printArray Remove type parameter section and replace
type parameter with actual type Object
1 public static void printArray( Object[] inputArray )
2 {
3 // display array elements
4 for ( Object element : inputArray )
Replace type parameter with
5 [Link]( "%s ", element );
actual type Object
6
7 [Link]();
8 } // end method printArray
16
Additional Compile-Time Translation Issues: Methods
That Use a Type Parameter as the Return Type
◼ Application
❑ Generic method
❑ Use Type parameters in the return type and parameter list
◼ Generic interface
❑ Specify, with a single interface declaration, a set of related types
❑ E.g., Comparable< T >
◼ Method [Link]( integer2 )
❑ Compare two objects of the same class
❑ Return 0 if two objects are equal
❑ Return -1 if integer1 is less than integer2
❑ Return 1 if integer1 is greater than integer2
17
1 // Fig. 18.5: [Link]
2 // Generic method maximum returns the largest of three objects.
3
4 public class MaximumTest
5 {
6 // determines the largest of three Comparable objects
7 public static < T extends Comparable< T > > T maximum( T x, T y, T z )
8 {
9 Type
T max = x; // assume x is initially the largest parameter
Typesection
parameter
specifies
is usedthat
in the
only
10 objectmax
Assign x to local variable returnthat
of classes typeimplement maximum
of methodinterface
11 if ( [Link]( max ) > 0 ) Comparable can be used with this method
12 max = y; // y is the largest so far Invokes method compareTo method
13
Comparable to compare y and max
14 if ( [Link]( max ) > 0 )
15 max = z; // z is the largest Invokes method compareTo method
16
Comparable to compare z and max
17 return max; // returns the largest object
18 } // end method maximum
19
18
20 public static void main( String args[] )
21 {
22 [Link]( "Maximum of %d, %d and %d is %d\n\n", 3, 4, 5,
23 maximum( 3, 4, 5 ) );
Invoke generic method
24 [Link]( "Maximum of %.1f, %.1f and %.1f is %.1f\n\n",
maximum with three integers
25 6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ) );
26 [Link]( "Maximum of %s, %s and %s is %s\n", Invoke
"pear",generic
method
27 "apple", "orange", maximum( "pear", "apple", maximum
"orange" ) ); with three doubles
28 } // end main
29 } // end class MaximumTest Invoke generic method
maximum with three strings
Maximum of 3, 4 and 5 is 5
Maximum of 6.6, 8.8 and 7.7 is 8.8
Maximum of pear, apple and orange is pear
19
Additional Compile-Time Translation Issues: Methods
That Use a Type Parameter as the Return Type
◼ Upper bound of type parameter
❑ Default is Object
❑ Always use keyword extends
◼ E.g., T extends Comparable< T >
❑ When compiler translates generic method to Java
bytecode
◼ Replaces type parameter with its upper bound
◼ Insert explicit cast operation
e.g., line 23 I preceded by an Integer cast
(Integer) maximum( 3, 4, 5 )
20
1 public static Comparable maximum(Comparable x, Comparable y, Comparable z)
2 {
3 Erasure replaces
Comparable max = x; // assume x is initially type
the largest parameter T
4 with its upper bound Comparable
5 if ( [Link]( max ) > 0 )
6 max = y; // y is the largest so far
7 Erasure replaces type parameter T
8 if ( [Link]( max ) > ) its upper bound Comparable
0with
9 max = z; // z is the largest
10
11 return max; // returns the largest object
12 } // end method maximum
21
Overloading Generic Method
◼ Generic method may be overloaded
❑ By another generic method
❑ By non-generic methods
◼ When compiler encounters a method call
❑ Search for most precise matching method first
◼ Exact method name and argument types
❑ Then search for inexact but applicable matching
method
22
Generic Classes
◼ Generic classes
❑ Use a simple, concise notation to indicate the actual
type(s)
❑ At compilation time, Java compiler
◼ ensures the type safety
◼ uses the erasure technique to enable client code to interact
with the generic class
◼ Parameterized classes
❑ Also called parameterized types
❑ E.g., Stack< Double >
23
Generic Classes (Cont.)
◼ Generic class declaration
❑ Looks like a non-generic class declaration
❑ Except class name is followed by a type parameter
section
24
Generic Classes (Cont.)
◼ Generic class at compilation time
❑ Compiler performs erasure on class’s type parameters
❑ Compiler replaces type parameters with their upper
bound
◼ Generic class test program at compilation time
❑ Compiler performs type checking
❑ Compiler inserts cast operations as necessary
29
Wildcards in Methods That Accept Type
Parameters
◼ Data structure ArrayList
❑ Dynamically resizable, array-like data structure
❑ Method add
❑ Method toString
◼ Motivation for using wildcards
❑ Implement a generic method sum
◼ Total the numbers in a collection
◼ Receive a parameter of type ArrayList< Number >
◼ Use method doubleValue of class Number to obtain the
Number’s underlying primitive value as a double value
30
1 // Fig. 18.14: [Link]
2 // Summing the elements of an ArrayList.
3 import [Link];
4
5 public class TotalNumbers
6 {
7 public static void main( String args[] )
8 {
9 Declare
// create, initialize and output ArrayList of Numbers and initialize
containing
10 // both Integers and Doubles, then display total of the numbers
array elements
11 Number[] numbers = { 1, 2.4, 3, 4.1 }; // Integers and Doubles
12 ArrayList< Number > numberList = new ArrayList< Number >();
13
14 for ( Number element : numbers ) Declare and initialize numberList,
15 [Link]( element ); // place each numberwhich stores Number objects
in numberList
16 Add elements in numbers array
17 [Link]( "numberList contains: %s\n", numberList );
to ArrayList numberList
18 [Link]( "Total of the elements in numberList: %.1f\n",
19 sum( numberList ) );
20 } // end main Invoke method sum to calculate the total
21
of the elements stored in numberList
31
22 // calculate total of ArrayList elements
23 public static double sum( ArrayList< Number > list )
24 { Method sum accepts an ArrayList
25 double total = 0; // initialize total that stores Number objects
26
27 // calculate sum
28 for ( Number element : list )
29 total += [Link]();
30 Use method doubleValue of class
31 return total; Number to obtain the Number’s underlying
32 } // end method sum primitive value as a double value
33 } // end class TotalNumbers
numberList contains: [1, 2.4, 3, 4.1]
Total of the elements in numberList: 10.5
32
Wildcards in Methods That Accept Type
Parameters (Cont.)
◼ Implementing method sum with a wildcard type argument in its
parameter
❑ Number is the superclass of Integer
❑ ArrayList< Number > is not a supertype of ArrayList< Integer >
❑ Cannot pass ArrayList< Integer> to method sum
❑ Use wildcard to create a more flexible version of sum
◼ ArrayList< ? extends Number >
◼ ? Represents an “unknown type”
◼ Unknown type argument must be either Number or a
subclass of Number
◼ Cannot use wildcard as a type name through method body
33
1 // Fig. 18.15: [Link]
2 // Wildcard test program.
3 import [Link];
4
5 public class WildcardTest
6 {
7 public static void main( String args[] )
8 {
9 // create, initialize and output ArrayList of Integers, then
10 // display total of the elements
11 Integer[] integers = { 1, 2, 3, 4, 5 };
12 ArrayList< Integer > integerList = new ArrayList< Integer >();
13
14 // insert elements in integerList
Declare and create ArrayList
15 for ( Integer element : integers ) integerList to hold Integers
16 [Link]( element );
17
18 [Link]( "integerList contains: %s\n", integerList );
19 [Link]( "Total of the elements in integerList: %.0f\n\n",
20 sum( integerList ) );
21 Invoke method sum to calculate the total
22 // create, initialize and output ArrayList of Doubles, then
integerList
of the elements stored in
23 // display total of the elements
24 Double[] doubles = { 1.1, 3.3, 5.5 };
25 ArrayList< Double > doubleList = new ArrayList< Double >();
26
27 // insert elements in doubleList
Declare and create ArrayList
28 for ( Double element : doubles ) doubleList to hold Doubles
29 [Link]( element );
30
34
31 [Link]( "doubleList contains: %s\n", doubleList );
32 [Link]( "Total of the elements in doubleList: %.1f\n\n",
33 sum( doubleList ) );
34 Invoke method sum to calculate the total
35 // create, initialize and output ArrayList of Numbers containing
of the elements stored in doubleList
36 // both Integers and Doubles, then display total of the elements
37 Number[] numbers = { 1, 2.4, 3, 4.1 }; // Integers and Doubles
38 ArrayList< Number > numberList = new ArrayList< Number >();
39
40 // insert elements in numberList Declare and create ArrayList
41 for ( Number element : numbers ) integerList to hold Numberss
42 [Link]( element );
43
44 [Link]( "numberList contains: %s\n", numberList );
45 [Link]( "Total of the elements in numberList: %.1f\n",
46 sum( numberList ) );
47 } // end main Invoke method sum to calculate the total
48
of the elements stored in numberList
49 // calculate total of stack elements 54 // calculate sum
50 public static double sum( ArrayList< ? extends Number > list )
55 for ( Number element : list )
51 {
52 double total = 0; // initialize total The56ArrayList argument’s
total element types
+= [Link]();
53 are 57
not directly known by the method, they
54 // calculate sum known toreturn
are 58 total;
be at least of type Number
59 } // end method sum
55 for ( Number element : list )
60 } // end class WildcardTest
56 total += [Link]();
57 integerList contains: [1, 2, 3, 4, 5]
Total of the elements in integerList: 15
58 return total;
59 } // end method sum doubleList contains: [1.1, 3.3, 5.5]
Total of the elements in doubleList: 9.9
60 } // end class WildcardTest
35 numberList contains: [1, 2.4, 3, 4.1]
integerList contains: [1, 2, 3, 4, 5] Total of the elements in numberList: 10.5
Total of the elements in integerList: 15
Generics and Inheritance: Notes
◼ Inheritance in generics
❑ Generic class can be derived from non-generic class
e.g., class Object is superclass of every generic class
❑ Generic class can be derived from another generic class
e.g., Stack is a subclass of Vector
❑ Non-generic class can be derived from generic class
e.g., Properties is a subclass of Hashtable
❑ Generic method in subclass can override generic method in
superclass
◼ If both methods have the same signature
36
Acknowledgements
◼ The course material used to prepare this
presentation is mostly taken/adopted from the
list below:
❑ Java - How to Program, 10th edition, Paul Deitel and
Harvey Deitel, Prentice Hall.
37