Generics in the Java Programming Language by Gilad Bracha

Generics in the Java Programming Language by Gilad Bracha

  • Submitted By: s1pjain
  • Date Submitted: 04/13/2010 1:54 AM
  • Category: Technology
  • Words: 2262
  • Page: 10
  • Views: 464

Generics in the Java Programming Language
Gilad Bracha July 5, 2004

Contents
1 Introduction 2 Defining Simple Generics 3 Generics and Subtyping 4 Wildcards 4.1 Bounded Wildcards . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Generic Methods 6 Interoperating with Legacy Code 6.1 Using Legacy Code in Generic Code . . . . . . . . . . . . . . . . . . 6.2 Erasure and Translation . . . . . . . . . . . . . . . . . . . . . . . . . 6.3 Using Generic Code in Legacy Code . . . . . . . . . . . . . . . . . . 7 The Fine Print 7.1 A Generic Class is Shared by all its Invocations . . . . . . . . . . . . 7.2 Casts and InstanceOf . . . . . . . . . . . . . . . . . . . . . . . . . . 7.3 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 Class Literals as Run-time Type Tokens 9 More Fun with Wildcards 9.1 Wildcard Capture . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Converting Legacy Code to Use Generics 11 Acknowledgements 2 3 4 5 6 7 10 10 12 13 14 14 14 15 16 18 20 20 23

1

1

Introduction

JDK 1.5 introduces several extensions to the Java programming language. One of these is the introduction of generics. This tutorial is aimed at introducing you to generics. You may be familiar with similar constructs from other languages, most notably C++ templates. If so, you’ll soon see that there are both similarities and important differences. If you are not familiar with look-a-alike constructs from elsewhere, all the better; you can start afresh, without unlearning any misconceptions. Generics allow you to abstract over types. The most common examples are container types, such as those in the Collection hierarchy. Here is a typical usage of that sort: List myIntList = new LinkedList(); // 1 myIntList.add(new Integer(0)); // 2 Integer x = (Integer) myIntList.iterator().next(); // 3 The cast on line 3 is slightly annoying. Typically, the programmer knows what kind of data has been placed into a particular list. However, the cast...

Similar Essays