Documentation
The Java™ Tutorials
Download Ebooks
Download JDK
Search Java Tutorials
Hide TOC
Generics (Updated)
Why Use Generics?
Generic Types
Raw Types
Generic Methods
Bounded Type Parameters
Generic Methods and Bounded Type Parameters
Generics, Inheritance, and Subtypes
Type Inference
Wildcards
Upper Bounded Wildcards
Unbounded Wildcards
Lower Bounded Wildcards
Wildcards and Subtyping
Wildcard Capture and Helper Methods
Guidelines for Wildcard Use
Type Erasure
Erasure of Generic Types
Erasure of Generic Methods
Effects of Type Erasure and Bridge Methods
Non-Reifiable Types
Restrictions on Generics
Questions and Exercises
Trail: Learning the Java Language
Lesson: Generics (Updated)
Section: Type Erasure
« Previous • Trail • Next »

# Erasure of Generic Methods

The Java compiler also erases type parameters in generic method arguments. Consider the following generic method:

    // Counts the number of occurrences of elem in anArray.
    //
    public static <T> int count(T[] anArray, T elem) {
        int cnt = 0;
        for (T e : anArray)
            if (e.equals(elem))
                ++cnt;
            return cnt;
    }

Because `T` is unbounded, the Java compiler replaces it with `Object`:

    public static int count(Object[] anArray, Object elem) {
        int cnt = 0;
        for (Object e : anArray)
            if (e.equals(elem))
                ++cnt;
            return cnt;
    }

Suppose the following classes are defined:

    class Shape { /* ... */ }
    class Circle extends Shape { /* ... */ }
    class Rectangle extends Shape { /* ... */ }

You can write a generic method to draw different shapes:

    public static <T extends Shape> void draw(T shape) { /* ... */ }

The Java compiler replaces `T` with `Shape`:

    public static void draw(Shape shape) { /* ... */ }

« Previous • Trail • Next »

Previous page: Erasure of Generic Types
Next page: Effects of Type Erasure and Bridge Methods