Generics in Java - Generic Method Definitions

Generic Method Definitions

Here is an example of a generic method using the generic class above:

public static Entry twice(T value) { return new SimpleImmutableEntry(value, value); }

Note: If we remove the first in the above method, we will get compilation error (cannot find symbol 'T') since it represents the declaration of the symbol.

In many cases the user of the method need not indicate the type parameters, as they can be inferred:

Entry pair = twice("Hello");

The parameters can be explicitly added if needed:

Entry pair = this.twice("Hello");

Note that you cannot use native types, ex:

Entry pair; // this fails. You have to use Integer instead.

There is also the possibility to create generic methods based on given parameters.

public T toArray(T... elements) { return elements; }

In such cases you can't use native types either, ex:

Integer array = toArray(1,2,3,4,5,6);

Read more about this topic:  Generics In Java

Famous quotes containing the words generic, method and/or definitions:

    “Mother” has always been a generic term synonymous with love, devotion, and sacrifice. There’s always been something mystical and reverent about them. They’re the Walter Cronkites of the human race . . . infallible, virtuous, without flaws and conceived without original sin, with no room for ambivalence.
    Erma Bombeck (20th century)

    There is no method but to be very intelligent.
    —T.S. (Thomas Stearns)

    The loosening, for some people, of rigid role definitions for men and women has shown that dads can be great at calming babies—if they take the time and make the effort to learn how. It’s that time and effort that not only teaches the dad how to calm the babies, but also turns him into a parent, just as the time and effort the mother puts into the babies turns her into a parent.
    Pamela Patrick Novotny (20th century)