Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>&lt;?&gt;</code> doesn't allow you to add objects in list. See the program below. It is specific type of list we have passed to method <code>&lt;?&gt;</code>. <br>Specific means, list was created with specific type and passed to <code>&lt;?&gt;</code> method <code>listAll</code>. Don't confuse with <strong>word</strong> <code>specific</code>. <br>Specific can be any normal object, like, Dog, Tiger, String, Object, HashMap, File, Integer, Long.... and the list is endless.<br><code>JLS</code> forces <code>&lt;?&gt;</code> method for <strong>not to</strong> perform <strong>add</strong> any <code>irrelevant objects</code> in called <code>&lt;?&gt;</code> method once you have defined <em>(defined in calling method not in <code>called-listAll</code> )</em> list containing <code>specific type</code> of object. <br>It is like <code>&lt;?&gt;</code> saying <strong>"don't touch me".</strong></p> <pre><code>public static void listAll(LinkedList list) { list.add(new String()); //works fine for(Object obj : list) System.out.println(obj); } public static void listAll(LinkedList&lt;?&gt; list) { list.add(new String()); //compile time error. Only 'null' is allowed. for(Object obj : list) System.out.println(obj); } </code></pre> <p>Now let's look at the different scenario. What will happen when we declare specific type like, Dog, Tiger, Object, String ..... anything. Let's change the method to <code>specific type</code>.</p> <pre><code>public static void listAll(LinkedList&lt;String&gt; list)// It is now specific type, 'String' { list.add(new String());//works fine. Compile time it knows that 'list' has 'String' for(Object obj : list) System.out.println(obj); } </code></pre>
 

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