Skip to Content
Java Pocket Guide, 4th Edition
book

Java Pocket Guide, 4th Edition

by Robert Liguori, Patricia Liguori
August 2017
Intermediate to advanced
290 pages
4h 10m
English
O'Reilly Media, Inc.
Content preview from Java Pocket Guide, 4th Edition

Chapter 16. Generics Framework

The Generics Framework, introduced in Java SE 5.0 and updated in Java SE 7 and 8, provides support that allows for the parameterization of types. Generics over Primitive Types is targeted for Java SE 10.

The benefit of generics is the significant reduction in the amount of code that needs to be written when developing a library. Another benefit is the elimination of casting in many situations.

The classes of the Collections Framework, the class Class, and other Java libraries have been updated to include generics.

See Java Generics and Collections by Philip Wadler and Maurice Naftalin (O’Reilly, 2009) for comprehensive coverage of the Generics Framework.

Generic Classes and Interfaces

Generic classes and interfaces parameterize types by adding a type parameter within angular brackets (i.e., <T>). The type is instantiated at the place of the brackets.

Once instantiated, the generic parameter type is applied throughout the class for methods that have the same type specified. In the following example, the add() and get() methods use the parameterized type as their parameter argument and return types, respectively:

public interface List <E> extends Collection<E>{
  public boolean add(E e);
  E get(int index);
}

When a variable of a parameterized type is declared, a concrete type (i.e., <Integer>) is specified to be used in place of the type parameter (i.e., <E>).

Subsequently, the need to cast when retrieving elements from things such as collections would ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java 8 Pocket Guide

Java 8 Pocket Guide

Robert Liguori, Patricia Liguori
Java 11 Cookbook - Second Edition

Java 11 Cookbook - Second Edition

Nick Samoylov, Mohamed Sanaulla

Publisher Resources

ISBN: 9781491938683Errata Page