Java Generic Parsing (as-is): Understanding Generics
WhatJava from the 1.0 version to the present 8, a very important change in the middle Java5, that is, the introduction of the generic mechanism. Java5 introduced generics, primarily to meet one of the earliest Java specifications specified in 1999. After about 5 years, the Expert group defined a set of generic specifications, which were implemented and then put into use by testing. Therefore, the generic type is Java5 later, for details, continue to look down.
Whyanother way to think, Java5 introduced generics, it must be it can bring benefits, otherwise bullish Java expert engineers will be spit slot.
Let's spit it out. How does a program with no generics write.
[CODE01]
ArrayList al = new ArrayList (); Al.add ("ysjian001"); Al.add (1); Al.add (New Object ());
This piece of code seems powerful, why? Because it seems to be able to add various types of objects to the collection (the int type will be boxed into an integer object type), it seems that some old programmers are inclined to do so, and they can confidently tell me the reason: I do what I want to save! Let's go ahead and take a look at the code below.
[CODE02]
The method that gets the value must be cast and then called to the corresponding object, string first = (string) al.get (0);
The value stored in the collection is for later removal, not System.out.println (first), where there is a casting problem, and often this type of coercion is allowed through the compiler, and the people who write the program make unintentional mistakes, The error has been cast, causing the program to run unsuccessfully. forcing a type conversion to fail because the type is not controlled by the compiler, see CODE01 calls the Add method of the ArrayList object, any type can be added, the compiler cannot perform error checking, and a security breach is buried, for example:
[CODE03]
ArrayList al = new ArrayList (); Error checking cannot be done, the File object can be added, and both the compiler and the runtime can pass Al.add (new file ()); String first = (string) al.get (0); Type conversion failure causes run to fail
a program without generics faces two problems:1. The compiler cannot perform type checking and can add objects of any type to the collection. 2. The type conversion failure at the time of value causes the program to run unsuccessfully. consequences of non-generic programs:1. The readability of the program is reduced because programmers can add arbitrary objects to the collection without being restricted. 2. The security of the program is questioned, and the type conversion failure will cause the program to run unsuccessfully.
JAVA5 generics provide a better solution:
type parameters (types parameters), using generic programs to improve the above code as follows:
[CODE04]
Arraylist<string> al = new arraylist<string> (); Al.add ("ysjian001"); Al.add (New Thread ()); The string type parameter is defined, and the file object is added with the error string first = al.get (0);//using generic post-values without type conversion
Q: Here, by contrast, the benefits of generics are not very clear? Why use generics? A: Because a compilation error is much better than a class casting exception at run time, the benefit of generics is that it improves the readability and security of the program, which is also the purpose of programming.
W.H.O.It is easy to use a generic class, and the classes in the collection frame are generic classes that are easy to use.
Some people would think of type limits why don't we just use arrays? This question is like asking why collections are better than arrays, arrays are fixed, and collections can be extended automatically. In fact, it's not that easy to implement a generic type. Look at an employee and manager inheritance structure:
[code05]
public class Employee { //... } public class Manager extends Employee { //... }
when we create and use a collection of employees, it is not complex to use:
[CODE06]
Arraylist<employee> employees = new arraylist<employee> (); Employees.add (New Employee ()); You can add employee employees.add (New Manager ()); You can add a manager because the manager is also an employee
the use of the above is no problem, because manager is a Employee, a typical inheritance relationship, but when the reverse, it may not be so smooth, such as:
[Code07]
Arraylist<manager> employees = new arraylist<manager> (); Employees.add (New Manager ()); Adding a manager is a normal operation //Employees.add (New Employee ()); You cannot add an employee at this time
The above code has a problem, and this demand is not nonexistent, then how to do? Don't worry, clever Java designers have invented a new and innovative concept, the wildcard type (wildcard type), here only need to know this concept, will be explained in detail later. Most application programmers do not have to consider how these generic collections work and how they are used by generics only if they are on a generic basis, like List, set, and map in a collection class. You may see ambiguous error messages when you mix different generic classes together, or when you join the legacy code that precedes Java5. This way, programmers need to learn Java generics to solve problems, rather than guessing in the program. Eventually, some programmers might want to implement their own generic classes and generic methods. The three levels of proficiency in the extraction of generic programming are:1. Use generics only. 2. Learn generics to solve some problems. 3. Master generics and implement your own generics.
HowHow to use generics sounds easy, because Sun's engineers have done a lot of work, and demand is always a little bit harsh and needs to be addressed because of the lack of ambiguity in type parameters, Or we need to implement our own generics to meet business needs, so learning and mastering generics is necessary.
generic class:from a simple start, define a generic class:
[Code08]
public class Couple<t> { private T wife; Private T husband; Public Couple (t wife, t husband) { this.wife = wife; This.husband = husband; } public void Setwife (T wife) {this. wife = wife;} public void Sethusband (T husband) {this. husband = husband;} Public T Getwife () {return wife;} Public T Gethusband () {return husband;} }
Couple couple class introduce a type parameter T, note that the type parameter is enclosed in angle brackets (< >), and placed after the class name, the Couple class in Code08 has a type parameter that can define multiple type parameters in the form of < T, K, V; the type parameter can be used to define the return type of the method, the parameter type, and the definition field or local variable, as in the following code
[Code09]
public class Couple<t, K, v> {...}//multiple type parameters separated by commas private T wife; The type parameter defines the domain public T getwife () {return wife;} Type parameter defines the type returned by the method
In the Java class Library, type variables are usually denoted by uppercase letters, E represents the element type of the collection, and K and V represent the type of the keyword and value of the mapping table, and T (U or s) represents any type. a simple generic class couple is defined, how to use it? Don't worry, we use this Couple class to specify a specific parameter type, such as the person class:couple<person>
[Code10]
Couple<person> (Person,person); Setwife (person); Sethusband (person); Person Getwife (); Person Gethusband ();
the code in CODE10 is a change in the type of couple after using the person type as the parameter type, note that this is not really a change in this way, but rather when we use that understanding, as to why? The erase will be explained in detail later.
Generic methods:What are the benefits of defining a generic class? In the previous example, this generic class would allow the user of the class to specify only the specific type when using it, which would improve the flexibility. So what's the definition of a generic method?
[Code11]
public class Genericmethod {public static <T> T getfirstvalue (t[] values) { return values[0]; } }
from the definition of a generic class that has already been learned and the generics method in Code11, it concludes that all
generics must first be defined in the form of <T> (multiple type parameters separated by commas, such as <k, v>) , which is a necessary prerequisite Looking back at the definition of the generic method above, defines a type parameter T for the method, specifies that the return value of the method is T, and the parameter of the method is an array of type T. The call to the method is more intuitive.
[Code12]
String[] values = {"Javase", "Corejava", "Effectivejava"}; String firstvalue = Genericmethod.<string>getfirstvalue (values);
I think the call is still a bit complicated, why use <String> before the method call? In fact, this is not necessary, when we pass the values of the string[] type to the method, the compiler is sufficient to judge that the concrete type of T is String, so <string> can be omitted.
[Code13]
String firstvalue = Genericmethod.getfirstvalue (values);
Summary:in this section, there is a general understanding of generics, what is it? Why do you use it? Who's going to use it? And how to use it? Through the practice of generic classes and generic methods, we feel how to implement your own generics, and the following section will explain the wildcard characters in generics, as well as the virtual machines ' erasure of generic classes and generic methods. Java Generic Parsing (01): Understanding Generics
Java Generic Parsing (01): Understanding Generics