First, the generic type:
Generic refers to a type of data that can be stored in a data type
1 ImportJava.io.*;2 ImportJava.nio.file.Files;3 Importjava.nio.file.Paths;4 Importjava.util.List;5 6 classMyclass<type>{7 Publictype[] tlist;8 PublicType TObject;9@SuppressWarnings ("Unchecked")TenMyClass (intMaxsize,type Object) { One This. Tlist = (type[])NewObject[maxsize]; A This. TObject =object; - } - PublicType Getmyobject () { the return This. TObject; - } - Publictype[] Getmylist () { - return This. tlist; + } - Public voidSetmyobject (Type object) { + This. TObject =object; A } at } - - Public classtest{ - Public Static voidMain (String args[])throwsIOException { -Myclass<string> Newone =NewMyclass<string> (5, "5"); - System.out.println (Newone.getmylist ()); in System.out.println (Newone.getmyobject ()); -Newone.setmyobject ("6"); to System.out.println (Newone.getmyobject ()); + } -}
1, the knowledge point of the variable definition:
About the definition of a generic variable (non-array):
1 class myclass<t>{2public T t; 3 MyClass (t newt) {4this . t = Newt; 5 } 6 }
About the generic definition of the data:
1 @SuppressWarnings ("Unchecked")2 myClass (int maxsize) {3 This . Tlist = (type[])new object[maxsize]; 4 }
2, the knowledge point 2--the generic type instantiation
Here you need to explicitly indicate the data type
1 New myclass<string> (5, "5");
Second, generic interface:
1 Public InterfaceMyinterface<t>{2 PublicT Next ();3 }4 //interface requires inheritance5 Public classMyClassImplementsmyinterface<string>{//explicitly defining a type when inheriting6 PrivateString[] Stringlist=Newstring[]{"A1", "B1", "C1"};7 @Override8 PublicString Next () {9Ramdom rand=NewRandom ();Ten returnStringlist[rand.nextint (3)]; One } A}
Three, generic method:
1. Generic method under generic class:
Generic parameters:
1 Public void Show (T t) {2 System.out.println (t); 3 }
Generic return value
1 Public T GetObject () {2 return This . T; 3 }
2, a separate generic method:
1 Public void out (T t) {2 System.out.println (t); 3 }
Java Beginner Note five: generics processing