Java Fundamentals Review-20 (generics)

Source: Internet
Author: User

1, because what type of elements in the collection can be stored. Causes the run-time classcastexception to be raised if a strong turn occurs. How to solve this problem? When you use a collection, you must explicitly specify the type of the elements in the collection. This approach is called: Generics.

2, the application of generics is divided into three kinds: the class containing the generic type, containing the generic interface, containing a generic method.

3. When generics are used, define the format: (1) modifier class name < variable representing generic type > {}

(2) Public <T> T[] toArray(t[] a) {}

(3) Modifier Interface interface Name < variable representing generic type > {}

4. What are the benefits of using generics?

A: The classcastexception of the runtime was transferred to the compile time and failed to compile. Avoid the trouble of type strong turn.

5, the use of generic wildcard environment: When the generic type cannot be determined, but to ensure the security of the code, this time with the generic wildcard <?> to ensure that the code compiled successfully.

Generic wildcard characters commonly used methods: (1) <? Extends a>//represents sub-class elements of Class A or class A

(2) <? Super a>//represents the parent element of Class A or class A

Java Fundamentals Review-20 (generics)

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.