4
1 http://www.tutorialspoint.com/java/java_generics.htm Java - Generics It would be nice if we could write a single sort method that could sort the elements in an Integer array, a String array or an array of any type that supports ordering. Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods or, with a single class declaration, a set of related types, respectively. Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time. Using Java Generic concept we might write a generic method for sorting an array of objects, then invoke the generic method with Integer arrays, Double arrays, String arrays and so on, to sort the array elements. Generic Methods: You can write a single generic method declaration that can be called with arguments of different types. Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately. Following are the rules to define Generic Methods: All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example). Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments. A generic method's body is declared like that of any other method. Note that type parameters can represent only reference types not primitive types (like int, double and char). Example: Following example illustrate how we can print array of different type using a single Generic method: public class GenericMethodTest {

Generics

  • Upload
    phani

  • View
    218

  • Download
    5

Embed Size (px)

DESCRIPTION

gen

Citation preview

1http://www.tutorialspoint.com/java/java_generics.htmJava - GenericsIt would be nice if we could write a single sort method that could sort the elements in an Integer array, aString array or an array of any type that supports ordering.Java Generic methods and generic classes enable programmers to specify, with a single method declaration,a set of related methods or, with a single class declaration, a set of related types, respectively.Generics also provide compile-time type safety that allows programmers to catch invalid types at compiletime.Using Java Generic concept we might write a generic method for sorting an array of objects, then invoe thegeneric method with Integer arrays, !ouble arrays, String arrays and so on, to sort the array elements.Generic Methods:"oucan write a singlegeneric methoddeclaration that canbecalledwith arguments of differenttypes.#ased on the types of the arguments passed to the generic method, the compiler handles each method callappropriately. $ollowing are the rules to define Generic %ethods& 'll generic method declarations have a type parameter section delimited by angle bracets () and*+ that precedes the method,s return type ( ) - * in the ne.t e.ample+. -ach type parameter section contains one or more type parameters separated by commas. ' typeparameter, also nown as a type variable, is an identifier that specifies a generic type name. /he type parameters can be used to declare the return type and act as placeholders for the types ofthe arguments passed to the generic method, which are nown as actual type arguments. ' generic method,s body is declared lie that of any other method. 0ote that type parameters canrepresent only reference types not primitive types (lie int, double and char+. Example:$ollowing e.ample illustrate how we can print array of different type using a single Generic method&public class GenericMethodTest{ // generic method printArray public static < E > void printArray( E[ inputArray ! {// "isplay array elements #or ( E element $ inputArray !{%ystem&out&print#( '(s ') element !*2 + %ystem&out&println(!*+public static void main( %tring args[ !{// ,reate arrays o# -nteger) "ouble and ,haracter-nteger[ intArray . { /) 0) 1) 2) 3 +*"ouble[ doubleArray . { /&/) 0&0) 1&1) 2&2 +*,haracter[ charArray . { 454) 4E4) 464) 464) 474 +*%ystem&out&println( 'Array integerArray contains$' !*printArray( integerArray !* // pass an -nteger array%ystem&out&println( '8nArray doubleArray contains$' !*printArray( doubleArray !* // pass a "ouble array%ystem&out&println( '8nArray characterArray contains$' !*printArray( characterArray !* // pass a ,haracter array+ +/his would produce following result&Array integerArray contains$/ 0 1 2 3 9Array doubleArray contains$/&/ 0&0 1&1 2&2 Array characterArray contains$5 E 6 6 7Bounded Type Parameters:/here may be times when you,ll want to restrict the inds of types that are allowed to be passed to a typeparameter. $or e.ample, a method that operates on numbers might only want to accept instances of 0umberor its subclasses. /his is what bounded type parameters are for./o declare a bounded type parameter, list the type parameter,s name, followed by the e.tends eyword,followed by its upper bound.Example:$ollowing e.ample illustrate how e.tends is used in a general sense to mean either 1e.tends1 (as in classes+or 1implements1 (as in interfaces+. /his e.ample is Generic method to return the largest of three2omparable objects&public class Ma:imumTest{ // determines the largest o# three ,omparable ob;ects public static T ma:imum(T :) T y) T = !{ ma: . y* // y is the largest so #ar+i# ( = !{ ma: . +return ma:* // returns the largest ob;ect + public static void main( %tring args[ ! {%ystem&out&print#( 'Ma: o# (d) (d and (d is (d8n8n') 1) 2) 3) ma:imum( 1) 2) 3 ! !* %ystem&out&print#( 'Ma:m o# (&/#)(&/# and (&/# is (&/#8n8n') 9&9) ?&?) @&@) ma:imum( 9&9) ?&?) @&@ ! !* %ystem&out&print#( 'Ma: o# (s) (s and (s is (s8n')'pear') 'apple') 'orange') ma:imum( 'pear') 'apple') 'orange' ! !* ++/his would produce following result&Ma:imum o# 1) 2 and 3 is 3Ma:imum o# 9&9) ?&? and @&@ is ?&?Ma:imum o# pear) apple and orange is pearGeneric Classes:' generic class declaration loos lie a non-generic class declaration, e.cept that the class name is followedby a type parameter section.'s withgenericmethods, thetypeparameter sectionof agenericclasscanhaveoneor moretypeparametersseparatedbycommas. /heseclassesarenownasparameteri3edclassesorparameteri3edtypes because they accept one or more parameters.Example:$ollowing e.ample illustrate how we can define a generic class&public class Ao: {private T t*public void add(T t! {this&t . t*+public T get(! {return t*4+public static void main(%tring[ args! { Ao: integerAo: . ne> Ao:(!* Ao: stringAo: . ne> Ao:(!*

integerAo:&add(ne> -nteger(/=!!* stringAo:&add(ne> %tring('5ello Borld'!!* %ystem&out&print#('-nteger Calue $(d8n8n') integerAo:&get(!!* %ystem&out&print#('%tring Calue $(s8n') stringAo:&get(!!*++/his would produce following result&-nteger Calue $/=%tring Calue $5ello Borld