Bounded WildCard

hi,
What is the exact use of <?> of this wildCard
Set<?> is it equal to Set<Object>
Can you also explain me, why this code is not compilling. I couldn't figure it out.
import java.util.ArrayList;
public class Generic1{
public static void main(String[] args){
ArrayList<? super Sub> list = new ArrayList<Sup>();
list.add(new Sup());
class Sup{
class Sub extends Sup{
}

See your other posting. This topic covered in the Generics tutorial:
http://java.sun.com/docs/books/tutorial/extra/generics/wildcards.html

Similar Messages

  • How to add item to a List with a bounded wildcard

    Hi,
    Is there a way to add a subtype instance to a List with a bounded wildcard? For example, say I have an
    abstract class called Car. Then I have 2 concrete subclasses--Ford and Toyota. Now say I have another
    class that contains a prepopulated list and is wildcard bounded like this: List<? extends Car> carList. I
    want to add a method where I pass in a Car subtype as a parameter and then add it into this list, e.g:
    public void addCar(Car car) {
    carList.add(car);
    Trying this, I keep getting "cannot find symbol" compilation errors. When I went back to read the Generics
    tutorial by Bracha, he mentions that explicitly adding a subtype, e.g. carList.add(new Ford()), can not be
    done. But here I'm adding the "upper bound" of the wildcard, i.e. the Car type. Therefore there should be no
    discrepancy between supertype and subtype an thus the carList.add(car) should be ok, IMO.
    Am I misunderstanding something with this logic? Also, if carList.add(car) can not be done, then how can
    I go about doing something similar which will allow me to add subtypes to a "generic" list?
    Thanks in advanced!
    -los

    I get a compilation error expecting an Object instead of a Car. Of course you did. List<? super Car> is a list into which you can put cars -- and possibly other stuff. List<? extends Car> is a list out of which you can get cars (possibly of different makes).
    Do you need a list that you can put cars in and get cars out? That's List<Car>
    This isn't a linguistic problem you are having; this is a design problem. If you have a function that takes an argument which is a list that you can put any kind of car into and be sure of getting a car out of, it isn't reasonable to pass in a List<Ford> (because the function might put in a Chevy) or a List<Object> (but there might be motorcycles already in there). By the requirements you have, you need a List<Car> and nothing else.
    Yes, you could use a cast, but all you are doing is circumventing the type system by saying "I know this List<Object> only has Cars in it."

  • Bounded Wildcard prob

    Hi All,
    Below is what the description says about "super"
    You can also specify a lower bound for a wildcard by adding a super clause to a wildcard declaration. Here is its general form:
    <? super subclass>
    In this case, only classes that are super classes of subclass are acceptable arguments. This is an exclusive clause, because it will not match the class specified by subclass
    However, pls look at the following code. According to the above description the below code(printXY_1(c4) call) should not compile and run, however is is running properly. I am wondering if i've missed something. Pls comment. Thank you in advance.
    class TwoD
         int x,y;
         public TwoD(int a,int b)
              x=a;y=b;
    class ThreeD extends TwoD
         int z;
         public ThreeD(int a,int b,int c)
              super(a,b);
              z=c;
    class FourD extends ThreeD
         int w;
         public FourD(int a,int b,int c,int d)
              super(a,b,c);
              w=d;
    class Coordinates<T extends TwoD>
         T [] coords;
         public Coordinates(T [] o)
              coords=o;
    public class BoundedWildcards
         public static void main(String args[])
              TwoD [] t2={ new TwoD(1,2),new TwoD(4,5)};
              Coordinates<TwoD> c2=new Coordinates<TwoD> (t2);
              ThreeD [] t3={ new ThreeD(1,2,3),new ThreeD(4,5,6)};
              Coordinates<ThreeD> c3=new Coordinates<ThreeD> (t3);
              FourD [] f4={ new FourD(0,1,2,3),new FourD(4,5,6,7)};
              Coordinates<FourD> c4=new Coordinates<FourD> (f4);
              System.out.println("\nPrint X & Y co-ordinates");
              printXY_1(c2);
              printXY_1(c3);
              printXY_1(c4);     }
                        static void printXY_1(Coordinates<? super FourD> obj)
              for(int i=0;i<obj.coords.length;i++)
                   System.out.println("X: "+obj.coords.x+"\tY: "+obj.coords[i].y);

    This is an exclusive clause, because it will not match the class specified by subclassThat doesn't agree with what I have read. (And it doesn't agree with what I would expect, either.) And what I have read is the first 200 pages of Angelika Langer's Generics FAQ document, which repeatedly says that <? super X> includes X. It specifically says that <? super Object> is legitimate but can only be satisfied by Object.

  • Javac bug with lower bounded wildcard?

    Hi all,
    I have found the below code snippet not to compile with javac (1.5 & 1.6) even though
    I think that it is correct. Also the Eclipse Java compiler accepts this code without errors.
    Can anyone confirm that this is a bug in javac or maybe explain why the code is really wrong as javac is claiming?
    Thanks a lot for any help!
    $$$ cat A.java
    interface I { }
    class C1 { }
    class C2 extends C1 implements I { }
    public class A<T extends C1 & I> {
    A<? super C2> a;
    $$$ javac A.java
    A.java:6: type parameter ? super C2 is not within its bound
    A<? super C2> a;
    ^
    1 error

    Hi Danny,
    thanks for your feedback. Actually, "? super C2" does not allow any arbitrary supertype of C2 since each type argument must also respect the bounds of the type parameter. Therefore, "? super C2" represents all supertypes of C2 which are also subtypes of C1 and I. In our case here, the only such type is C2.
    Here is also an attempt at showing that the code is correct based on the JLS3: Any type parameter is correct iff it is a subtype of all the types in the bound of the type parameter. To check this, you should take the capture conversion (JLS3 5.1.10) of "? super C2" which is a fresh type variable, let's say CAP, with the upper bound "C1 & I" which clearly is a subtype of the type parameter T as it has the same types in the bound. Or am I just missing something?

  • Why wildcards?

    Why do I need wildcards when I it seems like everything I can do with them I can achieve using an extra type parameter?
    For example I can convert:
    public double sum(List<? extends Number> list){
        double sum=0;
        for(Number n: list){
            sum += n.doubleValue();
        return sum;
    }to:
    public <E extends Number> double sum(List<E> list){
        double sum=0;
        for(Number n: list){
            sum += n.doubleValue();
        return sum;
    }It seems to me like I can do this for every (upper bounded) wildcard occurance. Am I wrong?
    -Jacob

    Why not read this page:
    http://java.sun.com/docs/books/tutorial/extra/generics/methods.html
    Mid page answers this exact ques

  • Typing rules for assigning non-wildcards to wildcards

    Hi all,
    I have the following code:
    public class A<T extends Number> {
         T t;
         public void foo() {
              Number number = null;
              Integer integer = null;
              A<? extends Integer> a1 = null;
              A<? super Integer> a2 = null;
              a1.t = null; // OK
              a1.t = integer; // Error
              a2.t = number; // Error
              a2.t = integer; // OK
    }The code contains four assignments of a non-wildcard type to a wildcard type. Two of them are correct, two are wrong. Now, intuitively, the following rules seem to hold for such assignments to upper/lower bounded wildcards:
    - Only the null-type can be assigned to an upper bounded (or unbounded) wildcard.
    - A non-wildcard type can be assigned to a lower bounded wildcard iff it can be assigned to the wildcard's lower bound.
    I think that the rules are quite intuitive but I would be interested in finding the formal typing rules for such assignments in the JLS. Can anyone provide a reference into the
    JLS which which cover the semantics of the above assignments?
    Any help would be really appreciated. Thanks a lot in advance!

    kablair & dannyyates,
    first of all, thanks a lot for taking you the time to explain the things to me that clearly! Sorry also for the somewhat confusing example by having chosen the final class Integer which is some kind of a special and limiting case.
    In any case, I have gone through the JLS yesterday as I was particularly interested in the role of capture conversion to formally explain the correctness of the above code and here are my conclusions I want to share with you: Actually, there seem to be no subtyping rules for wildcards because you always apply capture conversion (JLS3 5.1.10) to wildcards before looking for their subtype relationship to other types. Capture conversion converts each wildcard to a new fresh synthetic type variable which has appropriate upper bounds and also a lower bound. Now, in the very last sentence of section 4.10.2 of the JLS3, it is stated that a type variable is a direct supertype of its lower bound which I think is the key point. This means that you can assign something to a type variable iff you can assign it to its lower bound.
    Now, capture conversion converts every unbounded or lower bounded wildcard into a type variable which has the null type as its lower bound. This formally shows that you can really just assign null to them as in the code above. Contrary, every lower bounded wildcard is capture converted to a type variable whose lower bound is the lower bound of the wildcard. So, again, you can assign it every type you can assign to that lower bound. This is also reflected in the above code.
    So, that's maybe the formal explanation for something which is intuitively clear anyway...

  • What is more flexible ?

    Hi,
    Reading the generics faq, I have encountered this text:
    "In general, if you have an API that only uses a type parameter T as an argument, its
    uses should take advantage of lower bounded wildcards (? super T). Conversely, if
    the API only returns T, you�ll give your clients more flexibility by using upper bounded
    wildcards (? extends T)."
    Could anybody please explain me how would somebody benefit
    by using this convention ? Any examples ?
    Thanks,
    Adrian

    Hi Simu,
    That's right - an excellent example :)
    Moreover - I do understand what you write here
    and why it's useful here. But according to what was
    written in the sun's faq (let me quote it again):
    "In general, if you have an API that only uses a type parameter T as an argument, its
    uses should take advantage of lower bounded wildcards (? super T). Conversely, if
    the API only returns T, you�ll give your clients more flexibility by using upper bounded
    wildcards (? extends T)."
    An example you could fit into this convention could be (let's quote again):
    public static <T> List<? extends T> doSomething(List<? super T> l) {
       return new ArrayList<T>();  // what else could I put in here ? I can't
                                                       //put just anything since I don't know what the T
                                                       //is going to be, so no subtypes available ...
                                                      //as for formal method's parameter l - there isn't
                                                      //any other benefit  then being able to invoke eg:
                                                      // l.add() .... or is there something else ?
    }So we accept a parameterized formal method's parameter whose
    type parameter is bounded wildcard. I understand that it is useful
    as we are able to call e.g.: l.add() But sometimes it is not that case
    and we want to accept List<? extends T>. So why does author assume that
    List<? super T> is in general better ? (Why is he assuming that in general
    we want to be able to call parameter's methods which have type parameter
    in its signature more often ?) And secondly, as I wrote as comment, what is
    the benefit of RETURNING List<? extends T> ?
    And have a look at what I wrote about copy method again:
    Original from Collections:
    public static <T> void copy(List<? super T> dst, List<? extends T> src) {}My propose:
    public static <T> void copy(List<? super T> dst, List<T> src) {}They BOTH work.
    Thanks for your patient :)
    Cheers,
    Adrian

  • " ? extends Classifier " not assignable to Classifier

    I am just trying to understand this
    My method is like this
    public List<? extends Classifier> getClassifiers(){
    Now if I use the loop like this I get the error "Type mismatch: cannot convert from element type ? extends Classifier to Classifier"
    for( Classifier c : getClassifiers()){
    I was hoping that a subtype of Classifier is assignable to Classifier.

    bounded wildcard is useful as an argument type so for example a method that processes List<Shape> can be passed a List<Rectangle>
    -- quote -- from http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
    Any drawing will typically contain a number of shapes. Assuming that they are
    represented as a list, it would be convenient to have a method in Canvas that draws
    them all:public void drawAll(List<Shape> shapes) {
        for (Shape s: shapes) {
            s.draw(this);
    }[i]Now, the type rules say that drawAll() can only be called on lists of exactly Shape:
    it cannot, for instance, be called on a List<Circle>. That is unfortunate, since all
    the method does is read shapes from the list, so it could just as well be called on a
    List<Circle>. What we really want is for the method to accept a list of any kind of
    shape:public void drawAll(List<? extends Shape> shapes) {
    }[i]There is a small but very important difference here: we have replaced the type
    List<Shape> with List<? extends Shape>. Now drawAll() will accept lists of
    any subclass of Shape, so we can now call it on a List<Circle> if we want.
    -- end quote --
    But for a return value, I cannot see any benefit of using a bounded wildcard List.
    But there is a problem, because you cannot do the assignment you are expecting. Here's why http://blogs.sun.com/roller/page/ahe/20040610
    I would suggest making your method signature
    public List<? extends Classifier> getClassifiers()

  • Java 5 wonderments

    Hey,
    1. Autoboxing - I could not get why do I need to use the Integer.valueOf(int) method when I have auto unboxing. Why the autoboxing \ unboxing and the Integer.valueOf(int) were added together to Java 5 and does the autounboxing also uses cache like the Integer.valueOf(int) method?
    2. Generics - What advantage do I have of using a non-bounded wildcard:
    void printCollection(Collection<?> c) {...}instead of
    void printCollection(Collection c) {...}Thanks.

    1) Integer.valueOf(int) was added in JDK 5. That is the reason I asked - why did they add it along with auto unboxing. When should I use the method?
    I agree that you need to think carefully when using autoboxing\unboxing because the JVM does conversions it is just automatic.
    So you need to think before you do:
    if (myInteger == 1 || myInteger == 5 || myInteger == 8) {..}and do this instead:
    int myInt = myInteger;
    if (myInt == 1 || myInt == 5 || myInt == 8) {..}2) There is no warnings when sending a generics collection to a method that gets an unparameterized collection.
    I still don't get it.

  • Generics

    It has been given in Java Complete Reference update1.5
    following lines in respect to Bounded Wildcards in chapter of Generics:-
    You can also specify a lower bound for a wildcard by adding a super clause to a wildcard declaration.Here is its general form:
    <? super subclass>
    In this case,only classes that are superclasses of subclass
    are acceptable arguments.This is an exclusive clause,because it will not match the class specified by subclass
    But when used super clause with wildcard characters it also allows the object of subclass.please can anybody explain this or is it written wrong in book
    help required urgently
    Thx in advance

    thank you
    so is it right that <? super sublclass> also allows objects of subclassbut i want to make a note of one thing that when this thing is used with a generic method it works properly i.e. you cannot pass an object of subclass
    so y there is different behaviour in generic class and generic methods?????
    Thx in advance

  • Using wildcard in return activity in bounded taskflow

    This is my situation:
    I have a page to which the user may only navigate through a router activity, and I want the user to be authenticated too. So I thought I'd set the router activity (and a filter) and the page inside a bounded taskflow.
    But now I have a problem exiting the bounded taskflow. I don't want to specify all the possible outcomes and create different return activities. I have tabs on each page and I want the user to be able to click a tab and go to that page. But when I set a wildcard the navigation doesn't work.
    What does work is this:
        <control-flow-rule id="__22">
          <from-activity-id id="__23">rr_start</from-activity-id>
          <control-flow-case id="__25">
            <from-outcome id="__28">toAvIndex</from-outcome>
            <to-activity-id id="__24">returnFromStartFlow</to-activity-id>
          </control-flow-case>
        </control-flow-rule>
        <task-flow-return id="returnFromStartFlow">
          <outcome id="__21">
            <name>toAvIndex</name>
          </outcome>
        </task-flow-return>But this allows me only to navigate to AvIndex and I have 4 more pages I want to navigate to.
    What I would like to have is this:
        <control-flow-rule id="__22">
          <from-activity-id id="__23">rr_start</from-activity-id>
          <control-flow-case id="__25">
            <from-outcome id="__28">*</from-outcome>
            <to-activity-id id="__24">returnFromStartFlow</to-activity-id>
          </control-flow-case>
        </control-flow-rule>
        <task-flow-return id="returnFromStartFlow">
          <outcome id="__21">
            <name>*</name>
          </outcome>
        </task-flow-return>and let the unbounded taskflow check the outcome and do the navigation. Could this be possible?

    Wendy,
    have you considered to use a taskflow template for the navigation and use this template for your taskflows?
    Only other thing which come to mind is to set a parameter from inside your flow and check this parameter in a method in the parent flow to decide where to go.
    Timo

  • Do wildcards have to be within bounds?

    Is it intended that the compiler accepts the following type declaration?
    class Wrapped<T extends Comparable> { ... }
    Wrapped<? super Number> wrapper3;  // <<<Number is not Comparable, and for this reason no supertype of Number is Comparable. Consequently the set of types denoted by Wrapped<? super Number> is empty. Why does the compiler allow nonsensical type declarations?
    The specification does not say anything about the lower bound of a wildcard, but I had expected that of course the lower bound of a wildcard is checked against the upper bound of the type parameter the wildcard stands for. No? Wrong idea?

    We've flipflopped on this issue a couple of times. At first we though we should check the bounds, but that isn't right, because then you can't write (ignoring the fact that Comparable is generic)
    Wrapped<? extends Number>
    This is perfectly harmless, and denotes a nontrivial and useful type. So we dropped the checking altogether. That is too relaxed, as you can see. Our current plan, due to Christian Plesner Hansen is:
    given this declaration "class C<T extends X>",
    * C<Y> is legal if Y <: X (the current rule)
    * C<? extends Y> is legal if Y is castable to X
    * C<? super Y> is legal unless Y cannot possibly be a subtype of X
    The prototype compiler doesn't currently have this rule nor "castable" implemented, nor are they specified in the jsr14 spec that I distributed. I'm working on this now, based on very nice code supplied by Christian, but I'm afraid I may not have it in the prototype until October.

  • Wildcard with multiple bounds

    Hi everyone,
    There is a nice explanation in Angelika Langer FAQ why there isn't
    thing such T super SomeType, but I couldn't find anything about
    multiple bounds on wildcards. Why is it not allowed ? What are the
    reasons ?
    Also, wildcards can extend arrays, like:
    List<? extends int[]> l=...1) What is the benefit of that ? What can I do with it comparing to:
    List<int[]> l=...2) Why isn't there type parameter counterpart ?
    MyClass<T extends int[]> {...}Perhaps if I get the answer to my first question, the second one
    will be obvious ... ;)
    Thanks a lot !
    Adrian

    You'll have to declare a type parameter T extends MyClass & MyInterface and make your list a List<T>.

  • Calling a bounded task flow from  an unbounded task flow

    How can I navigate from an unbounded task flow to a bounded task flow....
    My situation is as follows:
    In the adfc-config.xml, I have a view activity ADMhome, Wildcard as well as a task-flow-call, admTaskFlow.  A control flow goes from the wildcard to ADMhome while another control flow goes from the wildcard to task-flow-call.
    I have a bounded task-flow "adm-task-flow" with two view actitivies: AdmListView and AdmPageView with AdmListView as the default activity. A Control flow goes from the AdmListView to AdmPageView, all pointing the page fragments
    I created another page ADMregion which is a  (jsf) where I dragged the adm-task-flow onto.
    When I ran the application, the home page displayed properly but when I clicked on a command button to invoke the "adm-task-flow", the application will not responded.
    When I looked at the log message, It gave this message:
    <TaskFlowCallXmlImpl> <parse> ADFc: /WEB-INF/adfc-config.xml:
    <TaskFlowCallXmlImpl> <parse> ADFc: Failed to parse element 'task-flow-reference'.
    <ActivityXmlImpl> <parse> ADFc: /WEB-INF/adfc-config.xml:
    <ActivityXmlImpl> <parse> ADFc: Activity metadata could not be parsed. [Activity Type, ID] = ['task-flow-call', ' admTaskFlow '].

    Thanks for this clarifications...
    I created a view activity in the adfc-config-xml and called the page (ADMregion) where the task flow was embedded. It worked well..
    Another clarification I want is this, when do I use a task flow call to call a task flow?  My thinking and my understanding was that when you create a task flow, you use a task flow call to invoke the task flow.
    Pls another aspect I want you to guide me is on calling a java class from jsf and jsff pages. Being new in these technologies, I have having some difficulties navigating and putting all of them together. My problem is this:
    I created a java class under the view package of Application Sources in the View Controller of my Application. The java class returns a value. I designed a jsff form with input fields and and command buttons. I want when I clicked on a command button to take a parameter from the input field and pass it to the java class, the after processing, the java class returns a value which I will place inside one of the input fields in my jsff form.

  • New Wildcard SSL certificate

    Guys,
    We had a certificate expire on our CAS servers that was used for webmail, autodiscover etc. WE had purchased a wildcard cert for use on the newly installed ADFS servers for our migration to office 365. Rather than renew the original SAN cert, I imported
    the wildcard cert into cas, (same domain name) bound the cert in IIS, then completed an IISRESET. Launched outlook again, it prompted to accept the new wildcard cert. I accepted it. Logged out of outlook, launched again, prompted again for certificate. I then
    installed the certificate via the prompts in outlook. Yet each time I launch outlook, it is still asking to accept certificate. Any thoughts?

    Guys,
    Thanks for the suggestions, but here is the fix.
    I finally received a call from MSFT in regards to the certificate popup in Outlook. From what I had written earlier, I was on the right track, but it was ultimately an autodiscover issue.
    For this conversation, my client’s domain name is Domain.com
    FQDN names of the CAS servers are CAS01.nyc.domain.com / CAS02.nyc.domain.com
    Now, all the steps that were completed, importing the *.domain.com cert into Exchange via EMC, and importing the cert using Certificate manager snap-in were successful. I was curious if the *.domain.com would cover a servers name if the server name was like
    my client, CAS01.nyc.domain.com. Typically it’s just CAS01.Domain.com. You would think so, but I was not totally convinced. MSFT did say that it is fine for the server, but, the AutodiscoverInternalURL CAS01.nyc.domain.com was the underlying problem. Once
    the outlook client tried to login, it used the AutodiscoverInternalURL, which was shown to be
    https://CAS01.nyc.Autodiscover.domain.com/Autodiscover/Autodiscover.xml . Same for CAS02
    So we ran the command below which removed the nyc,
    Set-ClientAccessServer –Identity CAS01 -AutoDiscoverServiceInternalUri
    https://CAS01.autodiscover.domain.com/autodiscover/autodiscover.xml
    Same for CAS02. Completed an IISRESET, all better now…….

Maybe you are looking for

  • Quick Look Index View and PDF hidden content

    I have come across an odd quirk of Quick Look in which the Index View is different from the regular view. The Quick Look Index View of two or more PDF files will show hidden page or image content, while the regular view of the individual files will n

  • New Computer, New Itunes, ... old Apple TV. how to modify content

    The Apple TV was originally setup on a Mac, and uploaded tons of movies to it. The MAC died last year, and was replaced with a PC. I've been able to watch all the content, and figured out how to stream to it by using itunes and activating "home shari

  • Best dock for sound system

    I'm looking for either a dock or a/v cable that will give me the best sound from a high-powered serious sound system, not a "micro" system. I've tried a Belkin audio cable connected to my headphone (audio out) jack but the sound is unacceptable. Is t

  • Non-void return type for Application Module Clients Interface

    Hello, can anyone guide me on how will I solve my problem. first of all, I'm using JDeveloper 10.1.3, I use JSF, ADF Faces, ADF Model, ADF Business Components. I made a web page that has a Transactional Capabilities, all is going smoothly, all data's

  • Thread grouped in Mail only in a single folder??

    Hi, in Lion there is the option to group in threads all the messages related to a single conversation, including trash, incoming, sent, etc... I am noticing that in iOS there is no this feature but only message of the same folder can be grouped in th