Java understands the basic meaning of generics

Source: Internet
Author: User
Tags uppercase letter

Java generics

Java generics (generics) is a new feature introduced in JDK 5, which provides a compile-time type-safe detection mechanism that allows programmers to detect illegal types at compile time.

The essence of a generic is a parameterized type, which means that the data type being manipulated is specified as a parameter.

Generic methods

You can write a generic method that can receive different types of arguments when it is called. Depending on the type of argument passed to the generic method, the compiler handles each method call appropriately.

The following is the rule that defines a generic method:

    • All generic method declarations have a type parameter declaration part (delimited by angle brackets) that is part of the type parameter declaration before the method return type (<E> in the following example).
    • 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).
Instance:
 Public classElementdemo { Public Static voidMain (string[] args) {//<Integer> Run-time types//with generics, if the instantiation is a defined type that is inconsistent with the type passed in by the object, it will error at compile time. test<integer> T1 =NewTest<>(); T1.add (666); Test<String> t2 =NewTest<>(); T2.add ("CJJ"); }}/*** "E" is not meaningful here, you can also use other letters instead of * Its function is to instantiate the test class, what type it will call what type*/classTest<e>{     Public voidAdd (e e) {System.out.println (e); }}
Attention:

Generics are named as long as they conform to the naming conventions of identifiers.
Customary generics are typically named with only one uppercase letter

<T> type
<E> element type
<K> Key
<V> value
<R> Result/return

Generic backwards compatibility

< extends class/interface >

Importjava.util.ArrayList;Importjava.util.List; Public classElementdemo { Public Static voidMain (string[] args) {//instantiate an array list object of type integer, with data stored in int type dataList<integer> in =NewArraylist<>(); In.add (1); In.add (2); In.add (3); In.add (4); In.add (5); In.add (6); //instantiates an array list object of type Double, in which the data stored is of type double.List<double> dos =NewArraylist<>(); Dos.add (3.6); Dos.add (4.2); Dos.add (6.8); Dos.add (7.7); Dos.add (0.2); //Calling Methodsprint (in);    Print (Dos); }        //write a new method to traverse the list of element types that are numbers//The element type is number or its subclass//The extends class/interface means passing in the class/interface or its subclass/Sub-interface object//The maximum type of the element that can be passed in is limited to number//specifies the upper limit of the generic type     Public Static voidPrint (LIST&LT;?extendsNumber>list) {                //no more elements can be added to the object within the method body, except nullList.add (NULL); //print elements inside an objectSystem.out.println (list); }}

The upward shape specifies the upper bound of the generic, and the upper bound subclass can pass in the object to the generic method.

Generic backwards compatibility

<? Extends class/interface >

Importjava.util.ArrayList;Importjava.util.List; Public classElementDemo1 { Public Static voidMain (string[] args) {List<String> str =NewArraylist<>(); Str.add (0, "CJJ");    Print (str); }        //the lower bound of the generic type//The incoming element type is a list of string and its parent class//the Super class/interface represents the object that passed in to the class/interface and its parent/parent interface//indicates that the minimum type passed in is string     Public Static voidPrint (LIST&LT;?SuperString>list) {                //elements can be added to the method bodyList.add ("Add");  for(Object o:list) {System.out.println (o); }    }}

The upward shape specifies the lower bound of the generic, and the lower bound Fu class can pass in the object to the generic method.

Java understands the basic meaning of generics

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: info-contact@alibabacloud.com 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.