java--generics

Source: Internet
Author: User

1. Simple generic type

Use object: Because the object class is the root of a class hierarchy, all classes in Java are fundamentally inherited from this class. So all classes can be transformed into object classes.

ImportJava.util.*; Public classEx7 {Static voidF (Object a) {System.out.println (a); }     Public Static voidMain (string[] args) {f ("233"); F (233); F (2.33); List<Object> list =NewArraylist<object>(); List.add ("233"); List.add (233); List.add (2.33);  for(Object a:list) {System.out.println (a); }    }}

The f () function here can handle three types of objects, and the list can hold three types of objects, but in fact they are all objects that are processed or stored first into object type.

Output:

2332332.332332332.33

In general, we only use containers to store objects that are always typed, and one of the primary purposes of generics is to specify what type of object the container is to hold and then the compiler to guarantee the correctness of the type.

To do this, you need to use the type parameter, surround it with angle brackets, put it behind the class name, and replace the type parameter with the actual type when you use the class.

 Public classEx7<t> {    voidF (T a) {System.out.println (a); }     Public Static voidMain (string[] args) {Ex7<String> Exstr =NewEx7<string>(); EXSTR.F ("233"); EX7<Integer> Exint =NewEx7<integer>(); EXINT.F (2); EX7<Double> Exdou =NewEx7<double>(); EXDOU.F (2.5); }}

When you create a Ex7 object, you must indicate what type of object you want to hold and place it in angle brackets. Then you can only deposit that type or its subclasses in this Ex7 object.

Output:

23322.5

2, a meta-group of class library

Sometimes we want to return more than one object at a time, but the return statement allows only a single object to be returned, so the workaround is to create an object that holds multiple objects that you want to return.

Such a concept is called a tuple, which is a single object that stores a set of objects directly in it, which allows the object to read the elements in it, but does not allow the new object to be stored in it. Because it is the yuan, so can only use can not be modified, to modify the need to get a new, but this is not important = =

classTwotuple<a,b>{     Public FinalA first;  Public FinalB Second;  PublicTwotuple (A A, b b) { first=A; Second=b; }     PublicString toString () {return"(" + First + "," + Second + ")"; }}classFivetuple<a,b,c,d,e>extendsTwotuple { Public FinalC Third;  Public FinalD Fourth;  Public FinalE Fifth;  PublicFivetuple (A A, B b,c c,d d,e E) {Super(A, b); Third=C; Fourth=D; Fifth=e; }     PublicString toString () {return"(" + First + "," + Second + "," + Third + "," + Fourth + "," + Fifth + "," + ")"; }}
    • Tuples can be of any length, creating two tuples of 2 and 5 lengths, respectively,
    • The pairs in tuples can be of any different type, but it is best to indicate their type for each object.
    • And what I said before can be read, but it's not allowed to store new elements and modifications, and final solves the problem.
    • ToString is only used to display the values in the list.
classnew1{}classnew2{} Public classEx8 {StaticTwotuple<new1,integer>f () {return NewTwotuple<new1,integer> (NewNew1 (), 2); }    StaticTwotuple<new1,double>F1 () {return NewTwotuple<new1,double> (NewNew1 (), 2.5); }    StaticFivetuple<new1,new2,integer,double,double>g () {return NewFivetuple<new1,new2,integer,double,double>                    (NewNew1 (),NewNew2 (), 2, 2.3, 2.3); }    StaticFivetuple<new1,new2,integer,integer,string>G1 () {return NewFivetuple<new1,new2,integer,integer,string>                    (NewNew1 (),NewNew2 (), 2, 2, "2"); }     Public Static voidMain (string[] args) {twotuple<new1,Integer> test =f ();        SYSTEM.OUT.PRINTLN (test);        System.out.println (F1 ());        System.out.println (g ());    System.out.println (G1 ()); }}

Output:

([email protected],2] ([emailprotected],2.5) ([email protected],[email protected]4e25154f, 2,2.3,2.3,) ([email protected],[email protected],2,2,2,)

3. Generic interface

InterfaceGenerator<t>{T next ();}classcoffee{Private Static LongCounter = 0; Private Final Longid = counter++;  PublicString toString () {returnGetClass (). Getsimplename () + "" +ID; }}classMochaextendscoffee{}classLatteextendscoffee{}classCappuccinoextendscoffee{} Public classEx9ImplementsGenerator<coffee>{    PrivateClass[] Type = {Mocha.class, Latte.class, Cappuccino.class}; PrivateRandom Rand =NewRandom (47);  PublicCoffee Next () {Try {            return(Coffee) type[rand.nextint (type.length)].newinstance (); } Catch(Exception e) {Throw NewRuntimeException (e); }    }     Public Static voidMain (string[] args) {Ex9 ex=NewEx9 ();  for(inti = 0; I < 5; i++) System.out.println (Ex.next ()); }}

The Generator<t> interface is a class that is specifically responsible for generating objects, where next is used to generate new objects, and when implementing this interface, you need to specify this T

Output:

Cappuccino 01234

Then there is an example of the class that generated the Fibonacci sequence:

InterfaceGenerator<t>{T next ();} Public classEx9ImplementsGenerator<integer>{    Private intCounter = 0;  PublicInteger Next () {returnFIB (counter++); }    Private intFibintN) {        if(N < 2)return1; returnFIB (n-2) + fib (n-1); }     Public Static voidMain (string[] args) {Ex9 ex=NewEx9 ();  for(inti = 0; I < 18; i++) System.out.print (Ex.next ()+ " "); }}

Output:

4. Generic method

To define a generic method, simply place the generic parameter list before the return value

 Public class EXP10 {    public <T>void  F (T x) {        System.out.println (X.getclass ()). GetName ());    }      Public Static void Main (string[] args) {        new  Exp10 ();        EX.F ("x");        EX.F (2);        EX.F (2.3);        EX.F (2l);        EX.F (4.55f);            }}

Output:

Java.lang.Stringjava.lang.Integerjava.lang.Doublejava.lang.Longjava.lang.Float

When creating a generic class, you must specify the type of the type parameter when you create the object, and when using a generic method, you usually do not need to indicate the type of the parameter, the compiler will find the specific type for us, which is called type argument inference, and we call F () like a normal method, just as f () is overloaded indefinitely.

java--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.