Notes for Using Generics in Java Development

Source: Internet
Author: User

1. Map <K, V> declaresThe generic type must be a class and cannot be a basic type. If it is a basic type, write it to the corresponding object type.

 

2. Map <K, V> map = new linkedhashmap <K, V> ();

When both sides have generics, the two generics must be the same.

Error-prone areas, such:

List <Object> List = new arraylist <string> (); No

List <string> List = new arraylist <Object> (); No

 

3.You can also allow only one side to have generics, while the other side to have no generics.

Map map = new linkedhashmap <K, V> ();

Map <K, V> map = new linkedhashmap ();

3. Generic isJavacUsed to limit the type of elements to be added to the set. However, when the compiler completesJavaProgramAfterClassFiles do not contain generic information. This process is called "erasure ". In this way, the program running efficiency can be avoided.

 

4. When a custom method contains multiple generics, the declared format is:

Public <T, E, F> void method (T, e, f ){}

 

5. When a method isStaticThen, this static method cannot use the generics declared on the class, and can only be declared on its own method.

Class demo <k>

{

Public static void method (K name) {}// Error

Public static <t> void F1 (t ){}

//Note that when the method declares the generic type, the position of the generic type should be next to that of the returned type.

}

 

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.