Dark Horse programmer-high-tech generic

Source: Internet
Author: User

----------------------
Android training and Java training. We look forward to communicating with you! ----------------------

 

Generic

Jdk1.5 new feature-generic use of generic sets, you can limit the elements in a set to a specific type, the set can only store the same type of objects, this is more secure; in addition, the compiler can obtain an object from the set. The Compiler also knows the object type and does not need to perform forced type conversion on the object, making it easier to use.
Some situations in which generics are used: Set and reflection
In generics? Wildcard
Use? Wildcards can reference other parameterized types ,? Variables defined by Wildcards are mainly used as references. You can call Methods unrelated to parameterization, rather than parameters.
In generics? Wildcard extension:
Limit the upper boundary of a wildcard:
Extends indicates that it is limited to number or a subclass limited to number.
Correct: vector <? Extends number> X = new vector <integer> ();
Error: vector <? Extends number> X = new vector <string> ();
Limit the bottom boundary of a wildcard:
Super indicates that only the integer parent class is limited, and the lower boundary is limited. The lowest down must also be integer.
Correct: vector <? Super integer> X = new vector <number> ();
Error: vector <? Super integer> X = new vector <byte> ();
You can specify your own wildcard characters.
Generic applications: hashmap cannot traverse map. Entry <>
Hashmap <string, integer> maps = new hashmap <string, integer> ();
Maps. Put ("Jeff", 22 );
Maps. Put ("ice", 22 );
Maps. Put ("juice", 1 );
Set <map. Entry <string, integer> entryset = maps. entryset ();
For (Map. Entry <string, integer> entry: entryset ){
System. Out. println (entry );
}
The internal principle and deeper application of generics:
Arraylist <string> arrlist1 = new arraylist <string> ();
Arraylist <integer> arrlist2 = new arraylist <integer> ();
System. Out. println (arrlist1.getclass () = arrlist2.getclass ());
Returns true.
After compilation, arrlist1 and arrlist2 use. getclass () to obtain bytecode.
Data of the arrlist2 and string types with reflection
Arrlist2.getclass (). getmethod ("add", object. Class). Invoke (arrlist2, "ABC ");
System. Out. println (arrlist2.get (1 ));
You can print the "ABC" at the corresponding position"
Method for defining generics:
The angle brackets used to place parameters of the generic type should appear after all the modifiers of the method and before the return type of the method, that is, before the return value. By convention, type parameters are usually represented by a single uppercase letter.
Only the reference type can be used as a parameter of the generic type. It cannot be a basic type.
Private Static <t> void swap (T [] A, int I, Int J ){
T temp = A [I];
A [I] = A [J];
A [J] = temp;
}
Type inference
Add (3, 5 );
Number X1 = add (3.5, 3 );
Object X2 = add (3, "ABC ");
In addition to using generics, you can use the extends qualifier. You can also use the extends qualifier when defining generics.
For example, the classgetannotation () method can be defined and multiple boundaries can be formulated with &, such as <v extends senrializable & cloneable> void method (){}
Generic can be used in common methods, constructor methods, and static methods, and the compiler cannot create arrays of type variables.
You can also use a type variable to indicate an exception, which is a parameterized exception. It can be used in the throws list of methods, but cannot be used in catch clauses.
Private Static <t extends exception> sayhello () throws t {}
A wildcard can have multiple types of parameters at the same time. Separate them with commas (,) in the angle brackets that define them. For example:
Public static <K, V> getvalue (K key) {return map. Get (key );}
Summary of exercises and types of custom generic methods:
The process for the compiler to determine the timing type parameter of a generic method is called process type judgment. type inference is equivalent to perceptual inference, and its implementation method is a very complicated process.
If the return type of the method is uncertain or the parameter type is uncertain, a generic method is defined.
Before returning a value to a generic method, use <t> to describe the type.
What type is passed after.
The specific rules are as follows:
1. When a type variable is applied only to all parameters and return values in the entire parameter list, it is determined based on the actual application type at the time of method call, it is easy to infer from the feeling that the type of the generic parameter is determined based on the type or return value of the parameter that is passed in the call method in a timely manner. For example:
Swap (New String [3], 3,4) --> static <E> void swap (E [] A, int I, Int J)
2. When a type variable is applied in multiple places of all parameters and return values in the entire parameter list, if the calling method is that the actual application types in multiple places correspond to the same type, this is easily inferred by feeling, for example:
Add (3, 5) --> static <t> Add (t a, t B)
3. When a type variable is applied to all parameters and return values in the entire parameter list, if the calling method is that the actual application types in multiple locations correspond to different types, the return value is not used. In this case, the maximum intersection type among multiple parameters in the partition. For example, the actual type of the following statement is number. The compilation is normal, but there is a problem during the running:
Fill (new integer [3], 3.5f) --> static <t> void fill (T [] A, t v)
4. When a type variable is most applied to all parameters and return values in the entire parameter type list, if the calling method is that the actual application types in multiple places correspond to different types, and use the return value. In this case, the type of the returned value is limited. For example, the actual type of the following statement is integer. The Compiler reports an error and changes the type of variable X to float, compare the error message reported by eclipse, and then change the variable X type to number, then there is no error:
Int X (3, 3.5f) static <t> t add (t a, t B)
Application of custom generic classes:
Dao abbreviation -- Data acess object --> crud adds, deletes, modifies, and queries creat, read, update, and delete databases.
If a generic parameter is required in multiple instance objects of the class, that is, the generic type referenced in these areas must be the same actual type, at this time, we need to use the generic type method for definition, that is, the Class-level generic syntax is as follows:
The following method can be used to specify the passed classes and returned classes.

public class GenericDao<T>{public void add(E x){}public E findById(int id){}public void delete(T obj){}public void delete(int id){}public void update(T obj){}public Set<T> findByConditions(String where){return null;}}

 

When using this function, you must specify the corresponding type. Class-level generic types are parameterized by I based on the type information specified when the class name is referenced.
Genericdao <reflectpoint> Dao = new genericdao <reflectpoint> ();
Pay attention to the following matters in the generic type:
1. When parameterized a generic type, the instance of the type parameter must be a reference type, not a basic type.
2. When a variable is declared generic, it can only be called by instance variables and methods (and embedded types), but cannot be called by static variables and static methods. Because static members are shared by all parameterized classes, static members should not have class-level type parameters.

 

----------------------
Android training and Java training. We look forward to communicating with you! ----------------------

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.