What you need to be aware of with Java generics

Source: Internet
Author: User

Static methods need to specify their type parameters to be generic

If the instance method in the non-fluidized type wants to be generic, it also needs to develop its type parameter.

The strength method in a generic type can directly use the type parameters of its type itself.

The paradigm is not covariant, that is, list<integer> is not a list<number> subclass.

It is not valid to instantiate an array of a generic type, that is, new list<string>[3], unless the type parameter is an unbound wildcard character, that is, the new list<?>[3 is legal.

Construction delay, we cannot construct an instance of that type through a type parameter when code is written, because we do not know how to construct, and the actual type of the type parameter is determined at run time.

We have a workaround for the problem described in Note 5 is list<string> list = (list<string>[]) new object[3], but if the runtime builds an array, the type information is determined by the runtime. Then change the wording t[] Tarray = (t[]) new object[3];

The above array construct is not recommended, and the best method is to pass the type information to the method, such as methods (class<v> type) {v[] array = (v[]) array.newinstance (type, length); You can refer to the implementation of the ToArray (t[] a) method of the ArrayList class.

Constructs a wildcard reference, and if the set is a set<?> type, then set<?> Set2 = new hashset<?> (set); is illegal, changed to set<?> Set2 = new HashSet <Object> (set); it's legal.

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.