Several places you should be aware of using Java generics

Source: Internet
Author: User

1, you can not use a local type (such as int float) to replace the generic

2. Run-time type checking, the different types of generic classes are equivalent (Pair and Pair belong to the same type Pair), which should be paid special attention to if a instanceof pair==true does not represent A.getfirst () The return value is a string type

3. Generic classes cannot inherit exception classes, that is, generic classes cannot be thrown as exceptions

4. You cannot define a generic array

5, can not use the generic structure of objects, namely: the new T (); It's wrong.

6. Generics cannot be used in the static method, nor can generic variables be decorated with the static keyword

7. Do not define equals (T x) in generic classes because there are also equals methods in the object class, and when the generic class is erased, the two methods conflict

8. There is no relationship between multiple classes derived from the same generic class, and no value can be assigned to each other, namely:

Pair P1; Pair P2; P1=P2; This assignment is wrong.

9, if a generic class also has a non-generic class of the same name, do not mix, adhere to the use of generic classes

Pair < manager > managerbuddies = new Pair < Manager > (CEO, CFO);

Pair rawbuddies = managerbuddies;

Here the compiler does not complain, but there are serious run-time error problems.

Related Article

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.