Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The question is vague, but I believe this excerpt from Angelika Langer's Java Generics FAQ answers it:</p> <blockquote> <h3>Which methods and fields are accessible/inaccessible through a reference variable of a wildcard parameterized type?</h3> <p>It depends on the kind of wildcard.</p> <p>Using an object through a reference variable of a wildcard parameterized type is restricted. Consider the following class: </p> <p>Example (of a generic class): </p> <pre><code>class Box&lt;T&gt; { private T t; public Box(T t) { this.t = t; } public void put(T t) { this.t = t;} public T take() { return t; } public boolean equalTo(Box&lt;T&gt; other) { return this.t.equals(other.t); } public Box&lt;T&gt; copy() { return new Box&lt;T&gt;(t); } } </code></pre> <p>When we use a reference variable of a wildcard instantiation of type Box to access methods and fields of the referenced object the compiler would reject certain invocations. </p> <p>Example (of access through a wildcard parameterized type): </p> <pre><code>class Test { public static void main(String[] args) { Box&lt;?&gt; box = new Box&lt;String&gt;("abc"); box.put("xyz"); // error box.put(null); // ok String s = box.take(); // error Object o = box.take(); // ok boolean equal = box.equalTo(box); // error equal = box.equalTo(new Box&lt;String&gt;("abc")); // error Box&lt;?&gt; box1 = box.copy(); // ok Box&lt;String&gt; box2 = box.copy(); // error } } </code></pre> </blockquote> <p>Essentially <code>?</code> has less information for the generic type system, and thus to enforce typesafety certain invokations must be rejected, because they're not typesafe.</p> <p>A <code>Box&lt;?&gt;</code> may be a <code>Box&lt;Integer&gt;</code>, a <code>Box&lt;String&gt;</code>, or even a <code>Box&lt;Box&lt;?&gt;&gt;</code>. Thus given a <code>Box&lt;?&gt; box</code>, <code>box.put("xyz")</code> must be rejected.</p> <h3>References</h3> <ul> <li><a href="http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html" rel="nofollow noreferrer">Angelika Langer's Java Generics FAQ</a> <ul> <li><a href="http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html#FAQ304" rel="nofollow noreferrer">Which methods and fields are accessible/inaccessible through a reference variable of a wildcard parameterized type?</a></li> </ul></li> </ul> <h3>Related questions</h3> <ul> <li><a href="https://stackoverflow.com/questions/2776975/how-can-i-add-to-list-extends-number-data-structures">How can I add to <code>List&lt;? extends Number&gt;</code> data structures?</a></li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload