Curious
Curious

Reputation: 921

confusion regarding wild card parametrized types

I had 2 classes as below. From my understanding compiler must not complain at line 4 (class WildCard) as my parametrized type is (Node? super Number> s0), as object is super to number in parametrized type. but compiler is complaining at 4,8 and 9. why so.

public class Node<E> {

    private E data;

    public void setData(E obj) {
        data = obj;
    }

    public E getData() {
        return data;
    }
}


public class WildCard {


    static void checkIt(Node<? super Number> s0)
    {
        Object object=new Object(); //1
        Number number =1.5; //2
        Integer integer=10; //3

        s0.setData(object); //4
        s0.setData(number); //5
        s0.setData(integer); //6

        object=s0.getData(); //7
        number=s0.getData(); //8
        integer=s0.getData(); //9
    }
}

Upvotes: 1

Views: 63

Answers (2)

Thomas
Thomas

Reputation: 88707

The problem is as follows:

Node<? super Number> means you could pass in any Node with a parameter that is of type Number or a super type, e.g. Object.

Since you don't know the exact type of that generic parameter some operations are not allowed.

Here's a short breakdown of why some lines compile and some don't:

  • s0.setData(object); doesn't compile because you could have a Node<Number> which would not all you to add an arbitrary object
  • s0.setData(number); compiles since Number matches all possible types for the parameter
  • s0.setData(integer); compiles because Integer extends Number and thus the line above applies

  • object=s0.getData(); compiles because any data object extends Object, always

  • number=s0.getData(); doesn't compile because you could have a Node<Object> and thus the data object might have a different type (e.g. String)
  • integer=s0.getData(); doesn't compile, same reason as the line above

Upvotes: 5

Paul Vargas
Paul Vargas

Reputation: 42020

The Java Language Specification says:

Wildcards may be given explicit bounds, just like regular type variable declarations. An upper bound is signified by the following syntax, where B is the bound:

? extends B

Unlike ordinary type variables declared in a method signature, no type inference is required when using a wildcard. Consequently, it is permissible to declare lower bounds on a wildcard, using the following syntax, where B is a lower bound:

? super B

Reference(T referent, ReferenceQueue<? super T> queue);

Here, the referent can be inserted into any queue whose element type is a supertype of the type T of the referent; T is the lower bound for the wildcard.

Upvotes: 0

Related Questions