0% found this document useful (0 votes)
7 views

Lecture8-1

This document covers Lecture 8-1 on Generic Classes in Java, detailing the concepts of generic programming, type parameters, and their implementation. It discusses generic classes, methods, constraints on type variables, and the limitations of Java generics, including type erasure. The lecture also includes announcements and a review of previous content related to collections in Java.

Uploaded by

kamishwang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Lecture8-1

This document covers Lecture 8-1 on Generic Classes in Java, detailing the concepts of generic programming, type parameters, and their implementation. It discusses generic classes, methods, constraints on type variables, and the limitations of Java generics, including type erasure. The lecture also includes announcements and a review of previous content related to collections in Java.

Uploaded by

kamishwang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

ICS 45J: Programming in Java

Lecture 8-1
Generic Classes

Emily Navarro
Announcements

• Guest lecture on Zoom this Thursday 2/27


• To get attendance credit, you must attend live on Zoom and stay the whole time
• For this week only, my office hours are Tuesday (today) 1-2pm instead of
Thursday
• Reminder: no late passes can be used on Lab 10
PART 1
Canvas Participation Quiz

Lecture 8-1: Lecture 7-2


Review

Text questions to (562) 684-8307


Last Time

• A collection groups together elements and allows them to be retrieved later


• A list is a collection that remembers the order of its elements
• E.g., ArrayList
• A set is an unordered collection of unique elements
• The HashSet and TreeSet classes both implement the Set interface

• A map keeps associations between key and value objects


• The HashMap and TreeMap classes both implement the Map interface
• A linked list consists of a number of nodes, each of which has a reference to the next node
• A stack is a collection of elements with “last-in, first-out” retrieval
• A queue is a collection of elements with “first-in, first-out” retrieval
• When removing an element from a priority queue, the element with the most urgent priority
is retrieved

Text questions to (562) 684-8307


PART 2
Learning Objectives

• To understand the objective of generic programming


• To implement generic classes and methods
• To explain the execution of generic methods in the virtual
machine
• To describe the limitations of generic programming in Java

Text questions to (562) 684-8307


Agenda

• Generic Classes and Type Parameters


• Implementing Generic Classes and Types
• Generic Methods
• Constraining Type Variables
• Type Erasure

Text questions to (562) 684-8307


Agenda

• Generic Classes and Type Parameters


• Implementing Generic Classes and Types
• Generic Methods
• Constraining Type Variables
• Type Erasure

Text questions to (562) 684-8307


Generic Classes and Type Parameters

• Generic programming: creating programming constructs that can


be used with many different types
• In Java, achieved with type parameters or with inheritance
• Type parameter example: Java’s ArrayList, e.g., ArrayList<String>
• Generic class: has one or more type parameters
• A type parameter for ArrayList denotes the element type:
public void add(E element)
public E get(int index)

Text questions to (562) 684-8307


Type Parameters
• Can be instantiated with class or interface type
ArrayList<BankAccount>
ArrayList<Measurable>

• Cannot use a primitive type as a type parameter:


ArrayList<double> // Wrong!
• Use corresponding wrapper class instead:
ArrayList<Double>
• Supplied type replaces type variable in class interface
• Example: add in ArrayList<BankAccount> has type variable E replaced with BankAccount:
public void add(BankAccount element)
• Type parameters make generic code safer and easier to read:
• Impossible to add a String into an ArrayList<BankAccount>

Text questions to (562) 684-8307


Agenda

• Generic Classes and Type Parameters


• Implementing Generic Classes and Types
• Generic Methods
• Constraining Type Variables
• Type Erasure

Text questions to (562) 684-8307


Implementing Generic Classes

• Example: simple generic class that stores pairs of arbitrary objects such as:
Pair<String, Integer> result = new Pair<>("Harry Hacker", 1729);

• Methods getFirst and getSecond retrieve first and second values of pair:
String name = result.getFirst();
Integer number = result.getSecond();

• Example of use: for a method that computes two values at the same time (method
returns a Pair<String, Integer>)
• Generic Pair class requires two type parameters, one for each element type
enclosed in angle brackets:
public class Pair<T, S>

Text questions to (562) 684-8307


Implementing Generic Types

• Use short uppercase names for type variables


• Examples:
Type Variable 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

• Place the type variables for a generic class after the class name, enclosed in angle
brackets (< and >)
public class Pair<T, S>

Text questions to (562) 684-8307


Declaring a Generic Class

Text questions to (562) 684-8307


Demo: Pair.java

Text questions to (562) 684-8307


Canvas Participation Quiz

Lecture 8-1: Generic


Classes and Types

Text questions to (562) 684-8307


PART 3
Agenda

• Generic Classes and Type Parameters


• Implementing Generic Classes and Types
• Generic Methods
• Constraining Type Variables
• Type Erasure

Text questions to (562) 684-8307


Generic Methods (I)

• Generic method: method with a type parameter


• Can be declared inside a generic or non-generic class
• Example: Declare a method that can print an array of any type:
public class ArrayUtil {
/**
Prints all elements in an array.
@param a the array to print
*/
public static <T> void print(T[] a) {. . .}
. . .
}

Text questions to (562) 684-8307


Implementing Generic Methods (I)

• Often easier to see how to implement a generic method by starting


with a concrete example
• Example: print the elements in an array of strings:
public class ArrayUtil {
public static void print(String[] a) {
for (String e : a) {
System.out.print(e + " ");
}
System.out.println();
}
. . .
}

Text questions to (562) 684-8307


Implementing Generic Methods (II)

• In order to make the method into a generic method:


• Replace String with a type parameter, say E, to denote the element type
• Add the type parameters between the method’s modifiers and return type
public static <E> void print(E[] a) {
for (E e : a) {
System.out.print(e + " ");
}
System.out.println();
}

Text questions to (562) 684-8307


Calling Generic Methods

• When calling a generic method, you need not instantiate the type
variables:
Rectangle[] rectangles = . . .;
ArrayUtil.print(rectangles);
• The compiler deduces that E is Rectangle
• You can also define generic methods that are not static
• You can even have generic methods in generic classes
• Cannot replace type variables with primitive types
• Example: cannot use the generic print method to print an array of type
int[]

Text questions to (562) 684-8307


Declaring a Generic Method

Text questions to (562) 684-8307


Canvas Participation Quiz

Lecture 8-1: Generic


Methods

Text questions to (562) 684-8307


PART 4
Agenda

• Generic Classes and Type Parameters


• Implementing Generic Classes and Types
• Generic Methods
• Constraining Type Variables
• Type Erasure

Text questions to (562) 684-8307


Constraining Type Variables (I)

• Type variables can be constrained with bounds


• A generic method, average, needs to be able to measure the objects
• Measurable interface from Lecture 5-1:
public interface Measurable {
double getMeasure();
}
• We can constrain the type of the elements passed in to average to those that
implement the Measurable type:
public static <E extends Measurable> double average(ArrayList<E> objects)

• This means “E or one of its superclasses extends or implements Measurable”


• We say that E is a subtype of the Measurable type

Text questions to (562) 684-8307


Constraining Type Variables (II)
• Completed average method:
public static <E extends Measurable> double average(ArrayList<E> objects) {
if (objects.size() == 0) {
return 0;
}
double sum = 0;
for (E obj : objects) {
sum = sum + obj.getMeasure();
}
return sum / objects.size();
}

• In the call obj.getMeasure():


• It is legal to apply the getMeasure method to obj
• obj has type E, and E is a subtype of Measurable

Text questions to (562) 684-8307


Constraining Type Variables - Comparable
Interface
• Comparable interface is a generic type
• The type parameter specifies the type of the parameter variable of the
compareTo method:
public interface Comparable<T> {
int compareTo(T other);
}

• String class implements Comparable<String>


• A String can be compared to another String
• But not with objects of a different class

Text questions to (562) 684-8307


Constraining Type Variables - Comparable
Interface
• When writing a generic method min to find the smallest element in an array list,
• Require that type parameter E implements Comparable<E>:
public static <E extends Comparable<E>> E min(ArrayList<E> objects) {
E smallest = objects.get(0);
for (int i = 1; i < objects.size(); i++) {
E obj = objects.get(i);
if (obj.compareTo(smallest) < 0) {
smallest = obj;
}
}
return smallest;
}
• Because of the type constraint, obj must have a method of this form:
int compareTo(E other)

• So the following call is valid:


obj.compareTo(smallest)
Constraining Type Variables – Multiple Bounds

• Very occasionally, you need to supply two or more type bounds:


<E extends Comparable<E> & Cloneable>

• extends, when applied to type parameters, actually means “extends


or implements”
• The bounds can be either classes or interfaces

Text questions to (562) 684-8307


Canvas Participation Quiz

Lecture 8-1: Constraining


Type Variables

Text questions to (562) 684-8307


PART 5
Agenda

• Generic Classes and Type Parameters


• Implementing Generic Classes and Types
• Generic Methods
• Constraining Type Variables
• Type Erasure

Text questions to (562) 684-8307


Type Erasure (I)

• The virtual machine erases type parameters, replacing them with their
bounds or Objects
• For example, generic class Pair<T, S> turns into the following raw
class:
public class Pair {
private Object first;
private Object second;

public Pair(Object firstElement, Object secondElement) {


first = firstElement;
second = secondElement;
}

public Object getFirst() { return first; }

public Object getSecond() { return second; }


}
Type Erasure (II)
• The same process is applied to generic methods
• In this generic method:
public static <E extends Measurable> E min(E[] objects) {
E smallest = objects[0];
for (int i = 1; i < objects.length; i++) {
E obj = objects[i];
if (obj.getMeasure() < smallest.getMeasure()) {
smallest = obj;
}
}
return smallest;
}
• The type parameter is replaced with its bound Measurable:
public static Measurable min(Measurable[] objects) {
Measurable smallest = objects[0];
for (int i = 1; i < objects.length; i++) {
Measurable obj = objects[i];
if (obj.getMeasure() < smallest.getMeasure()) {
smallest = obj;
}
}
return smallest;
}
Limitations of Java Generics (I)

• Knowing about type erasure helps you understand limitations of Java generics
• You cannot construct new objects of a generic type
• For example, trying to fill an array with copies of default objects would be wrong:
public static <E> void fillWithDefaults(E[] a) {
for (int i = 0; i < a.length; i++)
a[i] = new E(); // ERROR
}

• Type erasure yields:


public static void fillWithDefaults(Object[] a) {
for (int i = 0; i < a.length; i++) a[i] =
new Object(); // Not useful
}

• To solve this particular problem, you can supply a default object:


public static <E> void fillWithDefaults(E[] a, E defaultValue) {
for (int i = 0; i < a.length; i++) {
a[i] = defaultValue;
}

Text questions to (562) 684-8307


Limitations of Java Generics (II)

• You cannot construct an array of a generic type:


public class Stack<E> {
private E[] elements;
. . .
public Stack() {
elements = new E[MAX_SIZE]; // Error
}
}
• Because the array construction expression new E[] would be erased to new Object[]
• One remedy is to use an array list instead:
public class Stack<E> {
private ArrayList<E> elements;
. . .
public Stack() {
elements = new ArrayList<E>(); // Ok
}
. . .
}

Text questions to (562) 684-8307


Limitations of Java Generics (III)

• Another solution is to use an array of objects and cast when reading elements from the array:
public class Stack<E> {
private Object[] elements;
private int currentSize;
. . .
public Stack() {
elements = new Object[MAX_SIZE]; // Ok
}
. . .
public E pop() {
size--;
return (E) elements[currentSize];
}
}

• The cast (E) generates a warning because it cannot be checked at compile time

Text questions to (562) 684-8307


Canvas Participation Quiz

Lecture 8-1: Type Erasure

Text questions to (562) 684-8307


Summary

• A generic Java class has one or more type parameters


• Type parameters make generic code safer and easier to read
• Type variables of a generic class follow the class name and are
enclosed in angle brackets
• Use type parameters for the types of generic instance variables,
method parameter variables, and return values
• A generic method is a method with a type parameter
• Type parameters can be constrained with bounds
• The virtual machine erases type parameters, replacing them with their
bounds or Objects

Text questions to (562) 684-8307


Announcements

• Guest lecture on Zoom this Thursday 2/27


• To get attendance credit, you must attend live on Zoom and stay the whole time
• For this week only, my office hours are Tuesday (today) 1-2pm instead of
Thursday
• Reminder: no late passes can be used on Lab 10

You might also like