Getting Started with Java-generics (i)
Generic programming means that the code you write can be reused by many different types of objects, and more importantly, it guarantees the security of the data type. But designing generics is not that easy, and what a generic programmer has to do is predict all the possible uses of all classes in the future.
One: Target
Generic programming is divided into 3 tiers, with the basic level being the use of generics-a collection of typical small ArrayList-without regard to how and why they work. Most program apes will stay on this level until there is a problem.
II: Simple Generic class
Package Sep22;public class Pair<t> {//generics can have multiple variables, such as the public class Pair<t,k>{}private T first;//t type variable private t SECOND;//T type of variable public Pair () {//constructor first=null;second=null;} Public Pair (T first,t second) {//constructor overwrite This.first=first;this.second=second;} Public T GetFirst () {return first;} public void Setfirst (T first) {This.first = first;} Public T Getsecond () {return second;} public void Setsecond (T second) {this.second = second;}}
You can then instantiate the object by substituting the type variable with the specific type, for this example:
Pair<string>
After instantiating an object, you can think of the constructor as a normal class constructor:
Pair<string> () pair<string> (String first,string Second)
and methods
String GetFirst () string Getsecond () void Setfirst (string) void Setsecond (String)
Three: Generic methods
Generics can also define generic methods in a normal class
Class arrayalg{public static <T> t Getmiddle (t ... a) { return A[A.LENGTH/2];}}
Congo says
- A generic class is a factory of ordinary class that produces classes of the corresponding type when instantiating an object.
Getting Started with Java-generics (i)