Core Java

Generic Programming

Copyright © Cay S. Horstmann 2016

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

Understand the interaction between generic types and inheritance

Inheritance and Subtype Relationships

Inheritance and Subtype Relationships

Wildcard Types

Use ? extends for Producers

Supertype Bounds

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