Spec-Zone .ru
спецификации, руководства, описания, API
Trail: Learning the Java Language
Lesson: Generics (Updated)
Section: Type Erasure
Erasure of Generic Methods
Home Page > Learning the Java Language > Generics (Updated)

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) { /* ... */ }

Problems with the examples? Try Compiling and Running the Examples: FAQs.
Complaints? Compliments? Suggestions? Give us your feedback.

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