Address http://blog.csdn.net/lirx_tech/article/details/51570138
1. The original intention of designing generics:
1) mainly to solve the problem that the Java container cannot remember the element type:
I. Since the beginning of Java design does not know what type of element will be stored in the container, so the element type is set to object, so that everything can be put!
II. But there are obvious drawbacks to this design:
A. The forced type conversion must be performed when the element is taken (although the set is not changed at run time by the element's "run-time type", that is, the getclass of the element returns the original type rather than the object);
B. If you accidentally add a different type of element to the collection, you may cause the type exception (especially when you compare equals, compare);
C. Because there are no types that require forced type conversions in many places, this increases the complexity of the programming and the Code is not beautiful (bloated) and is more difficult to maintain;
2) concept definition of generics:
I. Starting with Java 5, the concept of parameterized type (parameterized type) has been introduced, and all Java collections have been modified to implement generics, allowing programs to specify the types of collection elements when creating collections, such as list<string> The name of the table this is a list that can only hold a string type;
Ii. generics (Generic): Refers to the parameterized type, the above list<string> is the parameterized type, therefore is the generic type, and String is the type parameter of the list<string> generic type;
3) Benefits of generics:
I. So that the collection can remember the element type, that is, when the element is removed without coercion type conversion, you can directly use the original type of reference to receive;
II. Once the sexual parameters are specified, the type of the elements in the collection is determined, and other types of elements cannot be added, otherwise they will be compiled and saved directly, which avoids the possibility of "accidentally putting other types of elements";
III. The above guarantees that if no warning is issued at compile time, the type conversion exception (ClassCastException) will not be generated at runtime;
Iv. clearly, generics make programming more generic, and the code is more concise and the code easier to maintain;
2. Create a generic Object-the diamond syntax for automatic type inference:
1) First, define generic references by using angle brackets to specify type parameters, such as:list<string> List, map<string, integer>, and so on, where String, Integer, and so on are type parameters;
2) Second, when you construct a generic object using a constructor, you can specify a type parameter or you can not specify it, for example:
i. list<string> List = new list<string> (); Of course it's right.
II. list<string> List = new list<> (); This is true because the type parameter of the list can be inferred from the reference!
!! But the reference type parameter is must add, otherwise cannot infer;
3) Since <> is much like a diamond, the above syntax is also called the diamond syntax;
4) Error Hint: reference to untyped parameter but constructor has type argument is wrong! For example, list list = new list<string> ();
!! As for why not, this will be described in detail in the section of the generic principle, here first remember that this is not the right thing!
! Anyway is a principle, generic reference is certain to specify the type parameter!!
5) Example:
[Java]View PlainCopy
- Public class Test {
- public static void Main (string[] args) {
- arraylist<string> list = new arraylist<> ();
- List.add ("Lala");
- List.add ("haha");
- //List.add (5);//type does not match, direct error!!
- List.foreach (Ele-System.out.println (ele)); //You can see that the removed ele does not need to force the type conversion, directly is the string type of
- //Description generic collection remembers the type of element, and the code is much simpler
- hashmap<string, integer> map = new hashmap<> ();
- Map.put ("abc", 15);
- Map.put ("Def", 88);
- Map.foreach (key, value), System.out.println (key + ":" + value); //You can see that key, value also does not have to force type conversions
- }
- }
3. Define generic classes, interfaces:
1) not only the Java collection is defined as generics, users can also define arbitrary generic classes, interfaces, as long as they are defined with <> to specify the type parameters;
2) For example: Publicclass Fruit<t> {...}, where <T> specifies the type parameter of the generic, this T is a type parameter name that the user can name arbitrarily (just like the parameter name of a method argument), Replace T with the specified specific type when defining the object of the generic to produce an instantiated generic object, such as:fruit<string> Fruit = new fruit<> (...);
3) Type parameters can be used in the entire interface, the body as a normal type, the collection all can use the ordinary type of place can use the type parameter, for example:
[Java]View PlainCopy
- Public interface Mygneric<e> {
- E Add (e val);
- Set<e> MakeSet ();
- ...
- }
!! as you can see, the type parameter can even be used within the interface/class to apply generics! For example, the MakeSet method above returns a generic set;
4) define a generic constructor: a generic constructor or the class name itself without using the diamond syntax, for example
[Java]View PlainCopy
- Public class Mygenric<t> {
- Mygeneric (...) { ... }
- ...
- }
! Define constructors without mygeneric<t> (...) { ... } , the diamond syntax is needed only when new is used;
4. Implement/Inherit generic interface/generic class:
1) Define generics and the concept of using generics: The main difference is to define and use
I. The Java method makes the analogy, the Java method uses the formal parameter (the virtual parameter) in the definition, but must pass the argument when the method (use method) is called;
II. Also has this characteristic, the generic type parameter and the method parameter, is also a kind of parameter, is only a special parameter, is used to represent the unknown type;
III. Therefore, generics must also be defined by using formal parameters (virtual arguments, which the user arbitrarily names), but when using generics (such as defining generic references, inheriting generics) you must use arguments, whereas generic arguments are specific types, such as String, A specific type such as Integer (which can also be a custom type, of course);
2) when defining a generic, use formal parameters, for example: public class Mygeneric<t> {...} T is a type parameter that you randomly name
3) When using generics, you must pass in the arguments:
I. When defining references (objects), there is no doubt that the argument must be:arraylist<string> list = ...; You must use a specific type, like this is a string instead of a formal parameter, that is, the argument
Ii. when implementing/inheriting a generic interface/class:
!! When you implement/inherit an interface/class, you are actually using the interface/class, for example: public class Son extends Father {...} Father This class is being used, no doubt, must be in use;
!! Therefore generics cannot actually inherit/implement, because the type argument must be passed to the generic when implementing/inheriting, and after the given argument it is a concrete type, it is no longer generic
!! Example: public class MyType extends Mygeneric<string> {...}//implements, extends must pass in type arguments, because generics are used!!
!! In principle, no programming language allows the generic template layer to inherit!!
4) After inheritance, the type parameters in all the methods in the parent class/interface will become the concrete type, you must use the specific type when you override these methods in the subclass, you cannot continue to use the generic type parameter, for example:
[Java]View PlainCopy
- Class Father<t> {
- T info;
- Public Father (T info) {
- this.info = info;
- }
- Public T Get () {
- return info;
- }
- Public t Set (t info) {
- T oldinfo = this.info;
- this.info = info;
- return This.info;
- }
- }
- Class Son extends Father<string> { //all the type parameters of the methods inherited from the parent class are all identified as String
- //So use specific type arguments when overwriting!
- Public Son (String info) {
- super (info);
- }
- @Override
- Public String Get () {
- return "haha";
- }
- @Override
- Public string Set (String info) {
- return "Lala";
- }
- }
!! This will guarantee that all three methods are inherited from the parent class, except that the type parameter T is instantiated as a string;
5. Generic parameter inheritance:
1) The above derived class is not generic, is an entity type, because its inherited generics are type arguments, and Java supports a special syntax that allows you to continue deriving generics from generics, while generic type parameters can continue to be passed down;
2) The syntax is as follows:
[Java]View PlainCopy
- Class Father<t> {...}
- Class Son<t> extends Father<t> {...}
! That is, the child generic can inherit the generic parameters of the parent generic, then the generic parameter T in the subclass is exactly the same as the parent class, or is used as usual (as normal as the parent class);
3) Note:
I. Here extends father<t>, so the parent generic Father is used, and according to the previous rules, it is necessary to specify the type arguments to a generic. So here's the syntax is a special syntax, Java specifically for this syntax open the back door, this syntax only when the type parameter passed the time will be used (that is, the above application);
II. Once this syntax is used, it means that the type parameter is inherited (that is, the parent class's T is passed to the subclass to continue to use, so the subclass is also a generic type like the parent class);
Iii. and once this syntax is used, the type parameters in the son<t> and extends father<t> in the subclass definition must be exactly the same as the type parameter names when the parent class is defined!!
A. All of the following three cases are all wrong (compile error All):
[Java]View PlainCopy
- Class Father<t> {}
- Class Son<e> extends Father<t> {}
- Class Father<t> {}
- Class Son<t> extends Father<e> {}
- Class Father<t> {}
- Class Son<e> extends Father<e> {}
!! Must all use the same type parameter name as the parent class (T)! This is a special rule for Java syntax;
4) In fact, many classes/interfaces in a Java container are defined by the inheritance of type parameters:
I. The most typical example is: public interface list<t> extends collection<t> {...}
II. Although "if a is the parent of B, but generic<a> is not the parent of generic<b>", "if A is the parent of B, then a<t> must be the parent of b<t>"! This is certain;
III. Because the type parameter inherits the definition way itself is:son<t> extends Father<t>, that father<t> must be Son<t> 's father Class!
6. When using generics, you can specify an argument without using the diamond syntax, directly bare with the type name:
1) For example:
I. Define a reference (object) when the bare class name: ArrayList list = new ArrayList ();//can also be written as ArrayList list = new arraylist<> ();
II. Implementation/Inheritance: public class MyType extends Mygeneric {...}
!! The type or interface used above is generic at the time of definition!! However, when using them, ignore the type parameters (no diamond is added);
2) Java rules that a generic is always generic anyway, anywhere, no matter how it is used, so this is where you ignore the type argument, which is also a generic, so what is the type of participation? Since we have not explicitly specified, will Java definitely assign a type argument to it implicitly?
3) The answer is yes, if you do not specify a type argument when using generics, then Java will use the generic "native type" as the type argument passed in!
!! So what is "native type"? Here is not introduced, will be in the next chapter of the "Generic principle" in detail decomposition;
!! But let's just say here that the native type of the Java collection is basically object, so like the above ArrayList list = new ArrayList (), the notation actually passes in the Object type argument, which is Arraylist<object >!
Java generics: Definitions of generics (classes, interfaces, objects), use, inheritance