Core Java

Generic Programming

Slide navigation: Forward with space bar, → arrow key, or PgDn. Backwards with ← or PgUp.

.jpg

Copyright © Cay S. Horstmann 2016

Except where otherwise noted, this work is licensed under .svg

Understand the advantages of generic programming

Why Generic Programming?

Type Parameters

Who Wants to Be a Generic Programmer?

Define a Simple Generic Class

A Pair<T> Class

public class Pair<T>
{
   private T first;
   private T second;

   public Pair() { first = null; second = null; }
   public Pair(T first, T second) { this.first = first; this.second = second; }

   public T getFirst() { return first; }
   public T getSecond() { return second; }

   public void setFirst(T newValue) { first = newValue; }
   public void setSecond(T newValue) { second = newValue; }
}

Type Variables

Define generic methods

Generic Methods

pair1

Know how to place restrictions on type variables

Bounds for Type Variables

pair2

Understand how generic code is translated to run on the Java virtual machine

Type Erasure

Cast Insertion

Bridge Methods

Bridge Methods

Calling Legacy Code

Be aware of restrictions and limitations of Java generics

Primitive Types

Runtime Type Inquiry

Creating Arrays

Varargs Warnings

Instantiating Types

Constructing Generic Arrays

Constructing Generic Arrays

Static Contexts

Exceptions

Clashes after Erasure

Java 9 News Flash - SafeVarags

.png

Understand the interaction between generic types and inheritance

Inheritance and Subtype Relationships

Inheritance and Subtype Relationships

.gif

Wildcard Types

Use ? extends for Producers

Supertype Bounds

.gif

Complex Wildcards

Unbounded Wildcards

Wildcard Capture

pairs3

Work with reflection and generic types.

The Generic Class Class

Generic Type Information in the Virtual Machine

genericReflection