The birth of a new technology, must have its historical reasons, through its history, but also to deepen the understanding of technology.
After the Java1.5 has been added to the use of generics, why increase generics? This article mainly discusses this problem.
First consider the following situation,
1 PackageCom.test.generic;2 3 Public classGenerictest {4 PrivateBoolean F;5 6 PublicBoolean getf () {7 returnF;8 }9 Ten Public voidsetf (Boolean f) { One This. F =F; A } - - the}View Code
1 PackageCom.test.generic;2 3 Public classGenericTest1 {4 PrivateString S;5 6 PublicString GetS () {7 returns;8 }9 Ten Public voidsets (String s) { One This. S =s; A } - -}View Code
The implementations of the two classes of the Generictest and GenericTest1 are the same, only the difference between the return value of the method and the member variable, and for some tool classes, it is often necessary to add a large number of classes for different types of data processing. This is a terrible and meaningless job for a project. Before generics, there is also a better way of handling, such as Class GenericTest2, we can use the type of object (interface or parent class) to implement the processing of different types of data. But this is not perfect, first of all, the data sent in and the data must be consistent, even if not consistent, the compiler will not error or the IDE will not alert the problem, and secondly, assume that the incoming object object is a string, but I take the value is cast to Integer, This in the compile time also will not error, the runtime will appear classcastexception, so the problem can not appear at compile time, for the program, robustness greatly reduced. As a result, generics have emerged after Java1.5 to solve these problems.
1 PackageCom.testeneric;2 3 Public classGenericTest2 {4 PrivateObject o;5 6 PublicObject Geto () {7 returno;8 }9 Ten Public voidSetO (Object o) { One This. O =o; A } - -}View Code
such as Class GenericTest3
1 PackageCom.test.generic;2 3 Public classGenerictest3<t> {4 PrivateT o;5 6 PublicT Geto () {7 returno;8 }9 Ten Public voidSetO (T o) { One This. O =o; A } - - Public Static voidMain (string[] args) { thegenerictest3<string> test1 =NewGenerictest3<string>(); - -Test1.seto ("Hello"); - System.out.println (Test1.geto ()); + } -}View Code
Such a class parameter type is T, then what type can be passed into the class, the implementation of the different types of data processing, and when used, if the use of the IDE, then once you confirm the type of T is, the compiler will prompt the type, as long as the compilation is not a problem, There is no problem at run time.
Why is Java adding generics after 1.5