28th: The flexibility of using the Fraiti API with restricted wildcard

Source: Internet
Author: User

The parameterized type is immutable. ,list<t1> and list<t2> do not have a parent-child type relationship for two different types of T1 and T2.

Consider:

 Public class Stack<e> {    public  Stack ();      Public void push (e e);      Public E pop ();      Public Boolean isEmpty ();}

Suppose you add a method that puts a series of elements into the stack sequentially:

 Public void pushall (iterable<e> src) {    for(e e:src)        push (e);}

If you try to do this:

New Stack<number>(); iterable<Integer> i = ...; S.pushall (integers);

Logically, this should be allowed, because integer is a subclass of number and should allow the integer to be placed on the stack of type number.

However, the actual operation will prompt iterable<number> and iterable<integer> incompatible.

A restricted wildcard type can handle this situation:

Pushall input parameters should not be "E iterable interface", but should be "E of a sub-type Iterable interface", modified to iterable<? Extends e>

Suppose you add a Popall method that pops each element from the stack and adds it to the specified collection:

 Public void Popall (collection<e> DST) {    while (!  IsEmpty) {        dst.add (pop ());}    }

As with unmodified Putall, the stack frame of type number should be allowed to be placed in a parent type, including number.

So, modify to:

 Public void Super e> DST) {    while (!  IsEmpty) {        dst.add (pop ());}    }

In the Putall method, the role of the input parameter is the producer, because the parameter provides the data to the stack to use, in the Popall method, the role of the input parameter is the consumer, because the stack provides the data for the parameter to use. In summary, if the parameterized type represents a T producer, use <? Extends T> If you represent a consumer of T, use < Super t>.

28th: The flexibility of using a restricted wildcard Fraiti API

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.