1, the use of generics, is conducive to reducing the coupling of code;
2, generics can solve the security problem of data type, can effectively avoid the occurrence of type conversion exception (classcastexception), make the program operation more secure;
3.
1 classPoint<t>{2 PrivateT x;3 PrivateT y;4 PublicT GetX () {5 returnx;6 }7 Public voidSetX (T x) {8 This. x =x;9 }Ten PublicT GetY () { One returny; A } - Public voidsety (T y) { - This. y =y; the } -}
4.
1 Public classGenericspoint {2 3 Public Static voidMain (string[] args) {4Point<integer> p =NewPoint<integer>();5 6P.setx (10);7P.sety (20);8 intx =p.getx ();9 inty =p.gety ();Ten System.out.println (x); One System.out.println (y); A } -}
The output is:
10
20
5.
1 Public classGenericspoint {2 3 Public Static voidMain (string[] args) {4Point<integer> p =NewPoint<integer>();5 6P.setx (10);7P.sety ("20");8 intx =p.getx ();9 inty =p.gety ();Ten System.out.println (x); One System.out.println (y); A } -}
An exception occurred:
Exception in thread "main" java.lang.Error:Unresolved compilation problem:
The method Sety (Integer) in the type point<integer> isn't applicable for the arguments (String)
6. Specify multiple generics
1 classNotepad<k,v>{2 PrivateK key;3 PrivateV value;4 PublicK GetKey () {5 returnkey;6 }7 Public voidSetkey (K key) {8 This. Key =key;9 }Ten PublicV GetValue () { One returnvalue; A } - Public voidSetValue (V value) { - This. Value =value; the } - } - Public classGenericsDemo09 { - + Public Static voidMain (string[] args) { -Notepad<string,integer> T =NewNotepad<string,integer>(); +T.setkey ("Zhangsan"); AT.setvalue (30); at System.out.println (T.getkey ()); - System.out.println (T.getvalue ()); - } -}
The output is:
Zhangsan
30
public class Genericspoint {
public static void Main (string[] args) {point<integer> p = new point<integer> ();p. SetX (Ten);p. sety; int x = P.getx (); int y = P.gety (); SYSTEM.OUT.PRINTLN (x); System.out.println (y);}}
One of the Java generics summary