Java-Generic understanding

Source: Internet
Author: User
Tags pear

Java generics provide a compile-time type-safe detection mechanism that allows programmers to detect illegal types at compile time. Java generics are needed when you need to use an algorithm that does not have a specific data type for the algorithm, or if you want to specify an upper or lower limit for the type value!

  Rules for generic methods:

    • All generic method declarations have a part of a type parameter declaration (delimited by angle brackets) that is part of the type parameter declaration before the method return type.
    • Each type parameter declaration section contains one or more type parameters, separated by commas between the parameters. A generic parameter, also known as a type variable, is the identifier used to specify a generic type name.
    • A type parameter can be used to declare a placeholder for the actual parameter type that returns a value type and can be obtained as a generic method.
    • The declaration of a generic method body is the same as other methods. Note that the type parameter can only represent a reference type, not the original type (like Int,double,char, and so on).


  First, define a generic method to print the object array elements

1      Public Static<E>voidPrintArray (e[] inputarray) {2          for(E elements:inputarray) {3 System.out.print (elements);4         }5     }6 7      Public Static voidMain (string[] args) {8Integer[] intarray={4,5,6,5,8};9Double[] Doublearray = {1.1, 2.2, 3.3, 4.4 };TenCharacter[] Chararray = {' H ', ' E ', ' l ', ' l ', ' O ' }; One  ASystem.out.println ("Integer array element is:" ); - PrintArray (intarray); -  theSystem.out.println ("\ n double-array element:" ); - PrintArray (doublearray); -  -System.out.println ("\ n character array element is:" ); + PrintArray (chararray); -}

  Second, define a generic method to sort the numbers (extends use)

1  Public Static<eextendsComparable>e searchmaxnumber (e x,e y,e z) {2E maxnumber=x;3         if(Y.compareto (MaxNumber) > 0){4Maxnumber=y;5         }6         if(Z.compareto (MaxNumber) >0){7Maxnumber=Z;8         }9         returnMaxNumber;Ten     } One  A      Public Static voidMain (string[] args) { -SYSTEM.OUT.PRINTF (the largest number in "%d,%d, and%d is%d\n\n", -3, 4, 5, Searchmaxnumber (3, 4, 5 ) ); theSystem.out.printf ("%.1f,%.1f and%.1f the largest number is%.1f\n\n", -6.6, 8.8, 7.7, Searchmaxnumber (6.6, 8.8, 7.7 ) ); -SYSTEM.OUT.PRINTF (the largest number in "%s,%s, and%s is%s\n", "pear", -"Apple", "Orange", Searchmaxnumber ("Pear", "apple", "orange" ) ); +}

  Iii. Definition of generic classes

1  Public classGenericityexam<e> {2 3    Privatee e;4 5     PublicE Get () {6        returne;7    }8 9     Public voidput (e e) {Ten         This. e=e; One    } A  -      Public Static voidMain (string[] args) { -Genericityexam<integer> Integerval =NewGenericityexam<integer>(); theGenericityexam<character> Charval =NewGenericityexam<character>(); -  -Integerval.put (NewInteger (10)); -Charval.put (NewCharacter (' s '))); +  -System.out.printf ("Integer value:%d\n", Integerval.get ()); +System.out.printf ("Character:%c\n", Charval.get ()); A     } at  -}

 Four, type wildcard upper bound generic type

public static <E> void Listgen (list<? extends e> data) {
for (E Listdata:data) {
SYSTEM.OUT.PRINTLN ("Data:" + listData);

public static void Main (string[] args) {
list<integer> listin = new arraylist<> ();
list<number> LISTNU = new arraylist<> ();

Listin.add (18);
Listin.add (45);
Listnu.add (314);
Listnu.add (789);

Listgen (Listin);
Listgen (LISTNU);
    • <? Extends e> indicates that the type represented by the wildcard is a subclass of type E.
    • <? Super e> indicates that the type represented by the wildcard is the parent class of type E.

When a generic is defined, it changes to the object type during run time.

Java-Generic understanding

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.