The essence of generics is to parameterize the data type, the value of the input parameter of the normal method can be changed, but the type (for example: String) is immutable, it makes it possible to overload the method in the face of different types of input parameters. Generics simply make this data type as variable as the value of the parameter.
Generics are divided into generic interfaces, generic classes, and generic methods. generic interface, generic class everyone is more familiar with, should have used list, ArrayList. List is a generic interface,ArrayList is a generic class, we often see the declaration of list <E>, the definition of New arraylist<e> (), in which E can be a string, can also define their own class. I feel that generics are basically enough for the JDK, and there are very few scenarios for custom usage. Instead, it is a generic method, which is very useful for parsing custom data structures, and is similar to the scenario of ToString.
----------------------------------------------------------- generic method Application instance ----------------------------------------- ---
Generic methods do not have to be inside a generic class
PackageTest;Importorg.junit.Test; Public classfanxing {/*** Defines a generic method that can also be declared as static *@paramT1*///Public static <T> void testfanxing (T t1) { Public<T>voidtestfanxing (T t1) {System.out.println (T1); } //Testing Generic Classes@Test Public voidtest1 () {fanxing FX=Newfanxing (); Fx.testfanxing (2); Fx.testfanxing (String); Fx.testfanxing (NewUser ("1", "QLQ")); }}//classes for testing generic classesclassuser{PrivateString ID; PrivateString name; PublicString getId () {returnID; } Public voidsetId (String id) { This. ID =ID; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } protectedUser (string ID, string name) {Super(); This. ID =ID; This. Name =name; } @Override PublicString toString () {return"User [id=" + ID + ", name=" + name + "]"; } }
Results:
----------------------------------------------------------- generic class application instance----------------------------------- ---------
PackageTest;Importorg.junit.Test;//can have one, or there can be more than one Public classFanxinglei<t, t2> { //Generic Properties PrivateT T1; PublicT getT1 () {returnT1; } Public voidsetT1 (T t1) { This. T1 =T1; } //Generic Methods Public voidtestfanxing (T2 T2) {System.out.println (T2); System.out.println ( This. getT1 ()); } Public Static voidMain (string[] args) {Fanxinglei<string, integer> Fanxinglei =NewFanxinglei<string, integer>(); FANXINGLEI.SETT1 ("Generic class"); Fanxinglei.testfanxing (4); }}
Test:
Java generic methods and the use of generic classes------------(v)