Java Generic Wildcard Learning--java Generic ' s wildcards

Source: Internet
Author: User

Java Generic ' s wildcards is a mechanism in Java generics aimed at making it possible to cast a collection of a certain CLA SS, e.g A, to a collection of a subclass or superclass of a. This is the text explains how.

Understanding: Java's generic wildcard mechanism is designed to implement type conversions for collections. For example, collection A, the collection of subclasses that are converted to a, or the parent class of a.

Here is a list of the topics covered:

    The Basic Generic Collection assignment problem

    Imagine you have the following class hierarchy:

     Public class A {}  Public class extends A {}  Public class extends A {}

    The classes B and C both inherit from A.

    Then look at these List variables:

    New Arraylist<a>(); ListNew arraylist<b> ();

    Can you set the to point to listA listB ? listB listA In other words, is these assignments valid:

    ListA == ListA;

    The answer is no in both cases. Here's why:

    listAin the can insert objects that is either instances of a, or subclasses of a (B and C). If you could does this:

    list<b> Listb = ListA;

    Then you could risk that listA contains Non-b objects. When you do try to take the objects out of your listB could risk to get non-b objects out (e.g. a A or a C). That breaks the contract of the listB variable declaration.

    Understanding: Lista can contain an instance of a, or it can contain instances of subclasses of a, such as B and C. When you point the LISTB reference to an instance of Lista, there is a danger, because when you call Listb's Get method you may take instance a or instance C, which violates the restriction of the variable type that the Listb declares (only instances of subclasses of instance B or B can be removed).

    Assigning listB to listA also poses a problem. This assignment, more specifically:

    ListA = Listb;

    If you could make this assignment, it would is possible to inserts A and C instances into the List<B> pointed to by listB . You could does listA that via the reference, which are declared to be of List<A> . Thus could insert Non-b objects into a list declared to hold B (or B subclass) instances.

    Understanding: It is also dangerous when you point the Lista reference to an instance of LISTB, because you can add an object of a or C to an instance of Listb, and it is an instance of the subclass of B that you can only join.

    When is Such Assignments Needed?

    The need for making assignments of the type shown earlier in this text arises when creating reusable methods that operate On collections of a specific type.

    Imagine you has a method that processes the elements of a List , e.g. print out all elements in the List . Here's how such a method could look:

     Public void processelements (list<a> elements) {   for(A o:elements) {      System.out.println (O.getvalue ());}   }

    This method iterates a list of a instances, and calls the getValue() method (imagine that the Class A has a method called getValue() ).

    As we have the already seen earlier in the this text, you can not call the This method with a List<B> or a List<C> typed variable as param Eter.

    Generic wildcards

    The generic wildcard operator is a solution to the problem explained above. The generic wildcards target, primary needs:

      • Reading from a generic collection
      • Inserting into a generic collection

    There is three ways to define a collection (variable) using generic wildcards. These is:

    list<?>           New arraylist<a>(); Listextendsnew arraylist<a>(); ListSuper   new arraylist<a> ();

    The following sections explain what these wildcards mean.

    The Unknown Wildcard

    List<?>means a list typed to an unknown type. This could is a, a List<A> List<B> , a List<String> etc.

    Since the know what type List of the is typed to, you can only read from the collection, and can only treat t He objects read as being Object instances. Here are an example:

     Public void processelements (list<?> elements) {   for(Object o:elements) {      System.out.println (o);   }}

    The processElements() method can now is called with any generic as List parameter. For instance a List<A> , a List<B> , List<C> , a List<String> etc. Here is a valid example:

    New Arraylist<a>();p rocesselements (ListA);

    The extends Wildcard boundary

    List<? extends A>means a List of objects that is instances of the Class A, or subclasses of a (e.g. B and C).

    When you know this instances in the collection be of instances of a or subclasses of a, it's safe to read the Instan Ces of the collection and cast them to A instances. Here are an example:

     Public void extends A> elements) {   for(A a:elements) {      System.out.println (A.getvalue ());}   }

    You can now call processElements() the method with either a List<A> , List<B> or List<C> . Hence, all of these examples is valid:

    New Arraylist<a>();p rocesselements (ListA); ListNew arraylist<b>();p rocesselements (LISTB); ListNew arraylist<c>();p rocesselements (LISTC);

    processElements()The method still cannot insert elements into the list, because you don ' t know if the list passed as parameter is Ty PED A to the class, B or C .

    The Super Wildcard boundary

    List<? super A>means that the list was typed to either the A class, or a superclass of a.

    When you know the list are typed to either a, or a superclass of a, it's safe to insert instances of a or subclasses of A (e.g. B or C) into the list. Here are an example:

     Public Static void Super a> list) {    List.add (new  A ());    List.add (new  B ());    List.add (new  C ());}

    All of the elements inserted here is either a instances, or instances of a ' s superclass. Since both B and C extend a, if a had a superclass, B and C would also is instances of that superclass.

    insertElements()either a List<A> , or a List typed to a superclass of a. Thus, this example are now valid:

    list<a>      ListA      new arraylist<a>(); insertelements (ListA); ListNew arraylist<object>(); insertelements (listObject);

    insertElements()The method cannot read from the list though, except if it casts the read objects to Object . The elements already present in the list when are insertElements() called could be of any type that's either an or superclass of a, But it isn't possible to know exactly which class it is. However, since any class eventually subclass you Object can read objects from the list if you cast them to Object . Thus, this is valid:

    Object object = List.get (0);

    It's not valid:

    A object = list.get (0);

    Java Generic Wildcard Learning--java Generic ' s wildcards

    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.