Java generics should pay attention to the details

Source: Internet
Author: User

1. A local type (such as int float) cannot be used to replace the generic type. For example, the List <integer> type cannot be used.

2. runtime type check. Different types of generic classes are equivalent (pair <string> and pair <employee> belong to the same
Type pair). Note that if a instanceof
If pair <string >== true, the returned value of A. getfirst () is a string type.

3. The generic class cannot inherit the exception class, that is, the generic class cannot be thrown as an exception.

4. Generic arrays cannot be defined.

5. The object cannot be constructed using generics, that is, t first = new T (); it is incorrect.

6. You cannot use generics in the static method, or modify generic variables with the static keyword.

7. Do not define equals (t x) methods in generic classes, because the equals method also exists in the object class. When the generic class is erased, the two methods conflict.

8. There is no relationship between multiple classes derived from the same generic class. values cannot be assigned to each other, that is, pair <number> P1; pair <integer> P2; p1 = P2; this assignment is incorrect.

9. If a generic class has a non-generic class with the same name, do not mix them. Always use a generic class.

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

Pair rawbuddies = managerbuddies; the compiler does not report errors, but there is a serious runtime error risk.

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: 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.