Java Reference
In-Depth Information
< formal_type_parameter_list > return_type identifier ( para-
meter_list )
The formal_type_parameter_list isthesameaswhenspecifyingageneric
type:itconsistsoftypeparameterswithoptionalbounds.Atypeparametercanappear
as the method's return_type , and type parameters can appear in the paramet-
er_list .Thecompilerinferstheactualtypeargumentsfromthecontextinwhichthe
method is invoked.
You'lldiscovermanyexamplesofgenericmethodsintheCollectionsFramework.For
example, its java.util.Collections class provides a public static <T
extends Object & Comparable<? super T>> T min(Collection<?
extends T> coll) method for returning the minimum element in the given
Collection according to the ordering specified by the supplied
java.util.Comparator instance.
Youcaneasilyconvert copyList() intoagenericmethodbyprefixingthereturn
typewith <T> andreplacingeachwildcardwith T .Theresultingmethodheaderis <T>
void copyList(List<T> src, List<T> dest) ,and Listing3-56 presents
itssourcecodeaspartofanapplicationthatcopiesa List of Circle toanother List
of Circle .
Listing 3-56. Declaring and using a copyList() generic method
import java.util.ArrayList;
import java.util.List;
class Circle
{
private double x, y, radius;
Circle(double x, double y, double radius)
{
this.x = x;
this.y = y;
this.radius = radius;
}
@Override
public String toString()
{
return "("+x+", "+y+", "+radius+")";
Search WWH ::




Custom Search