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)

    Methinks the human method of expression by sound of tongue is very elementary, & ought to be substituted for some ingenious invention which should be able to give vent to at least six coherent sentences at once.
    Virginia Woolf (1882–1941)

    What I do not like about our definitions of genius is that there is in them nothing of the day of judgment, nothing of resounding through eternity and nothing of the footsteps of the Almighty.
    —G.C. (Georg Christoph)