Java Generic Learning Example _java

Source: Internet
Author: User

Java generics (generics) is a new feature introduced by JDK5 that allows the use of type parameters (types Parameter) when defining classes and interfaces. The declared type parameters are replaced with specific types when used, and now the main application of generics is in the new collection class framework in JDK5, where Map and list are useful. The advantage of this is self-evident that we can extend more of the class, the disadvantage, in fact, is his advantage, because this requires us to use the generic class, we should be very clear to their own code, we can not use the wrong type.

The most basic generic class

Copy Code code as follows:

Package com.garinzhang.javabase.generic.e1;

/**

* The most basic generic class, the type is defined by itself

* @author Garin Zhang

*

* @param <T>

*/

public class Point<t> {

Private T var;

Public T GetVar () {

return var;

}

public void SetVar (T var) {

This.var = var;

}

}

Package com.garinzhang.javabase.generic.e1;

public class Genericexample {

/**

* @param args

*/

public static void Main (string[] args) {

point<string> p = new point<string> ();

P.setvar ("coder");

System.out.println (P.getvar ());

}

}

Multiple generic types

Copy Code code as follows:

Package com.garinzhang.javabase.generic.e2;

/**

* Multiple generic types, generally multiple preferably with letters near T, such as S,R, etc.

* @author Garin Zhang

*

* @param <T>

* @param <S>

*/

public class Notepad<t, s> {

Private T key;

private S value;

Public T Getkey () {

return this.key;

}

Public S GetValue () {

return this.value;

}

public void Setkey (T key) {

This.key = key;

}

public void SetValue (S value) {

This.value = value;

}

}

Package com.garinzhang.javabase.generic.e2;

public class Genericexample {

/**

* @param args

*/

public static void Main (string[] args) {

notepad<string, integer> p = new notepad<string, integer> ();

P.setkey ("coder");

P.setvalue (99999);

System.out.println ("key:" + P.getkey ());

System.out.println ("Value:" + p.getvalue ());

}

}

Use wildcard character "?" in method parameters.

Copy Code code as follows:

Package com.garinzhang.javabase.generic.e3;

/**

* This example is key in the Main method

* @author Garin Zhang

*

* @param <T>

*/

public class Info<t> {

Private T key;

Public T Getkey () {

return this.key;

}

public void Setkey (T key) {

This.key = key;

}

@Override

Public String toString () {

return this.key.toString ();

}

}

Package com.garinzhang.javabase.generic.e3;

/**

* Use wildcard characters in method parameters

* @author Garin Zhang

*

*/

public class Genericexample {

/**

* @param args

*/

public static void Main (string[] args) {

info<string> i = new info<string> ();

I.setkey ("coder");

Fun (i);

Info<integer> j = new info<integer> ();

J.setkey (9999);

Fun (j);

}

public static void Fun (Info<?> temp) {

System.out.println ("Content:" + temp);

}

}

Failed upward transition

Copy Code code as follows:

Package com.garinzhang.javabase.generic.e4;

/**

* This example is key in the Main method

* @author Garin Zhang

*

* @param <T>

*/

public class Info<t> {

Private T key;

Public T Getkey () {

return this.key;

}

public void Setkey (T key) {

This.key = key;

}

@Override

Public String toString () {

return this.key.toString ();

}

}

Package com.garinzhang.javabase.generic.e4;

public class Genericexample {

/**

* @param args

*/

public static void Main (string[] args) {

info<string> Streg = new info<string> ();

Info<object> Objeg;

Compile error ' Type Mismatch:cannot convert from info<string> to Info<object> '

Transition up failed, String-> Object

Objeg = Streg;

}

}



The use of generics in interfaces

Copy Code code as follows:

Package com.garinzhang.javabase.generic.e5;

/**

* This example is key in the Main method

* @author Garin Zhang

*

* @param <T>

*/

Interface Info<t> {

Public T GetVar ();

}

Package com.garinzhang.javabase.generic.e5;

/**

* Generic class

* @author Garin Zhang

*

* @param <T>

*/

public class Infoimpl<t> implements info<t> {

Private T var;

Public Infoimpl (T var) {

This.setvar (VAR);

}

public void SetVar (T var) {

This.var = var;

}

Public T GetVar () {

return This.var;

}

}

Package com.garinzhang.javabase.generic.e5;

/**

* Non-generic class

* @author Garin Zhang

*

* @param <T>

*/

public class InfoImpl1 implements info<string> {

Private String var;

Public InfoImpl1 (String var) {

This.setvar (VAR);

}

public void SetVar (String var) {

This.var = var;

}

Public String GetVar () {

return This.var;

}

}

Package com.garinzhang.javabase.generic.e5;

public class Genericexample {

/**

* @param args

*/

public static void Main (string[] args) {

info<string> Streg = new infoimpl<string> ("coder");

System.out.println ("Content:" + Streg.getvar ());

info<string> strEg1 = new InfoImpl1 ("Coder1");

System.out.println ("Content:" + Streg1.getvar ());

}

}

Wildcard characters and extends, Super's use

Copy Code code as follows:

Package com.garinzhang.javabase.generic.e6;

/**

* This example is key in the Main method

* @author Garin Zhang

*

* @param <T>

*/

public class Info<t> {

Private T key;

Public T Getkey () {

return this.key;

}

public void Setkey (T key) {

This.key = key;

}

@Override

Public String toString () {

return this.key.toString ();

}

}

Package com.garinzhang.javabase.generic.e6;

public class Genericexample {

/**

* @param args

*/

public static void Main (string[] args) {

info<string> Streg = new info<string> ();

Streg.setkey ("coder");

Compile the error "the Method fun (info<.? extends Number>) in the type genericexample are not applicable for the arguments (info& Lt string>) "

Uptypelimit (i);

Use the Integer,number type to

info<integer> Integ = new info<integer> ();

Integ.setkey (9999);

Uptypelimit (INTEG);

Compile the error "the Method Downtypelimit (info<. Super string>) in the type genericexample are not applicable for the argument S (info<integer>) "

Downtypelimit (INTEG);

The use of Super,downtypelimit can only receive string itself and object

View the inheritance relationship of string, no other classes inherited, only object

Downtypelimit (Streg);

info<object> Objeg = new info<object> ();

Objeg.setkey (999);

Downtypelimit (Objeg);

}

/**

*;? Extends t> represents the upper bound of a type, which indicates that a parameterized type may be a subclass of T or T

* @param Temp

*/

public static void Uptypelimit (INFO<? extends Number> temp) {

System.out.println ("Content:" + temp);

}

/**

*;? The super t> represents the lower bound of the type (called a supertype qualifier in the Java core), indicating that the parameterized type is a supertype of this type (the parent type) until the object

* In this case, it means that T can only be object or string because string only inherits from Object

* @param Temp

*/

public static void Downtypelimit (info<. Super String> temp) {

System.out.println ("Content:" + temp);

}

}

Method generics, methods inside multiple generics

Copy Code code as follows:

Package com.garinzhang.javabase.generic.e7;

/**

* Method Generics, methods inside multiple generics

* @author Garin Zhang

*

* @param <T>

*/

public class Info {

/**

* Format: Method modifier pay < comma-separated list > Return value type method name (argument list)

* For example: public <t, s> t fun (T T, s)

* @param t

* @param s

* @return

*/

Public <t, s> t fun (T T, s) {

System.out.println (S.tostring ());

return t;

}

}

Package com.garinzhang.javabase.generic.e7;

public class Genericexample {

/**

* @param args

*/

public static void Main (string[] args) {

Info info = new info ();

String str = info.fun ("coder", "Print second generic param");

System.out.println (str);

int i = Info.fun ("Print second param again");

System.out.println (i);

}

}

The generic type that is passed in or returned in the method is determined by the type of parameter that is set when the method is invoked

Copy Code code as follows:

Package Com.garinzhang.javabase.generic.e8;

/**

* Extends

* @author Garin Zhang

*

* @param <T>

*/

public class Info<t extends Number> {

Private T var;

Public T GetVar () {

return This.var;

}

public void SetVar (T var) {

This.var = var;

}

@Override

Public String toString () {

return this.var.toString ();

}

}

Package Com.garinzhang.javabase.generic.e8;

public class Genericexample {

/**

* @param args

*/

public static void Main (string[] args) {

Info<integer> Integ = Fun (30); Here the type has been determined to be integer

System.out.println (Integ.getvar ());

}

/**

The generic type that is passed in or returned in the * method is determined by the type of parameter that is set when the method is invoked

* @param param

* @return

*/

public static <t extends number> info<t> fun (T param) {

info<t> temp = new info<t> ();

Temp.setvar (param);

return temp;

}

}

Let the method pass in two parameter types consistently

Copy Code code as follows:

Package com.garinzhang.javabase.generic.e9;

/**

* View Main

* @author Garin Zhang

*

* @param <T>

*/

public class Info<t> {

Private T var;

Public T GetVar () {

return This.var;

}

public void SetVar (T var) {

This.var = var;

}

@Override

Public String toString () {

return this.var.toString ();

}

}

Package com.garinzhang.javabase.generic.e9;

public class Genericexample {

/**

* @param args

*/

public static void Main (string[] args) {

info<string> i1 = new info<string> ();

I1.setvar ("Hello");

info<string> i2 = new info<string> ();

I2.setvar ("coder");

info<integer> i3 = new info<integer> ();

I3.setvar (999);

Add (I1, i2);

Compile error "The method Add (info<t>, info<t>) in the type genericexample isn't applicable for the arguments (INFO&L T String>, info<integer>) "

Add (I1, i3);

}

/**

* The two parameter types passed into the method must be consistent

* @param param

* @return

*/

public static <T> void Add (info<t> i1, info<t> i2) {

System.out.println (I1.getvar () + ":" + I2.getvar ());

}

}

Generics, variable parameters, similar to arguments objects in JavaScript

Copy Code code as follows:

Package com.garinzhang.javabase.generic.e10;

public class Genericexample {

/**

* @param args

*/

public static void Main (string[] args) {

Integer i[] = Fun (1, 2, 3, 4, 5, 6);

Fun2 (i);

}

public static <T> t[] Fun (T.. Arg) {

return arg;

}

public static <T> void Fun2 (T param[]) {

SYSTEM.OUT.PRINTLN ("Generic array:");

for (T T:param) {

System.out.println (t + ",");

}

}

}



Generic nesting: Using a generic class as a parameter, and determining the return value based on the return value type
Copy Code code as follows:

Package com.garinzhang.javabase.generic.e11;

/**

* Accept two generic types

* @author Garin Zhang

*

* @param <T>

*/

public class Info<t, v> {

Private T var;

private V value;

Public T GetVar () {

return This.var;

}

public void SetVar (T var) {

This.var = var;

}

Public V GetValue () {

return this.value;

}

public void SetValue (V value) {

This.value = value;

}

@Override

Public String toString () {

return this.var.toString ();

}

}

Package com.garinzhang.javabase.generic.e11;

/**

* Accept 1 Generic types

* @author Garin Zhang

*

* @param <T>

*/

public class Demo<s> {

Private S info;

Public Demo (S info) {

This.setinfo (info);

}

public void SetInfo (S info) {

This.info = info;

}

Public S GetInfo () {

return this.info;

}

}

Package com.garinzhang.javabase.generic.e11;

Import java.util.List;

Import com.google.common.collect.Lists;

public class Genericexample {

/**

* @param args

*/

public static void Main (string[] args) {

Demo<info<string, integer>> D;

Info<string, integer> i;

i = new info<string, integer> ();

I.setvar ("coder");

I.setvalue (999);

D = new demo<info<string,integer>> (i);

System.out.println ("Content:" + d.getinfo (). GetVar ());

System.out.println ("Content:" + d.getinfo (). GetValue ());

System.out.println (Query (1, 2, 3, 4, 5). ToString ()); [1, 2, 3, 4, 5]

Warning "Type safety:a generic array of object&comparable<?>&serializable is created for A varargs parameter"

System.out.println (Query (1, 2, 3, "StringType"). toString ()); [1, 2, 3, StringType]

System.out.println ("I", "AM", "a", "coder"). ToString ());//[I, am, a, coder]

list<string> list = lists.newarraylist ("I", "AM", "a", "coder");

System.out.println (List.tostring ()); [I, am, a, coder]

}

/**

* A generic type is determined by the return value, and the return value type within this method is automatically generated by the definition of the method

* @param elements

* @return

*/

public static <E> list<e> query (E.. elements) {

Https://github.com/exitsoft/exit-web-framework/commit/1d2f1098a2a4b6abab175b793e2308aa8bd0ea16.

Import com.google.common.collect.Lists;

<dependency>

<groupId>com.google.guava</groupId>

<artifactId>guava</artifactId>

<version>16.0.1</version>

</dependency>

return lists.newarraylist (elements);

}

}

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.