Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is not how you create a generic class. If you use a raw type of your generic class, then all the parameterized type used inside the class, loose their type information. So, for <code>GenericTest</code> raw type, the <code>getKeys()</code> method signature changes to:</p> <pre><code>public Collection getKeys() { return null; } </code></pre> <p>So, if you iterate over <code>getKeys()</code> method of <code>GenericTest</code> raw type, you will get <code>Object</code>, and not <code>String</code>, which I don't see why you expect.</p> <p>From <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.8" rel="nofollow">JLS Section 4.8 - Raw Types</a>:</p> <blockquote> <p>The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) M of a raw type C that is not inherited from its superclasses or superinterfaces is the raw type that corresponds to the erasure of its type in the generic declaration corresponding to C.</p> </blockquote> <hr /> <p>You should really use <code>GenericTest&lt;T&gt;</code> as parameter type in your method, instead of raw type. And change the return type of <code>getKeys</code> to <code>Collection&lt;T&gt;</code>.</p> <p>Change your class to:</p> <pre><code>public class GenericTest&lt;T&gt; { public Collection&lt;T&gt; getKeys() { return null; } public void copy(GenericTest&lt;T&gt; a_from) { for (T x : a_from.getKeys()) { } } } </code></pre> <p>The type <code>T</code> is infered from the parameterized type you create for this generic class. For <code>GenericTest&lt;String&gt;</code>, <code>T</code> will be infered as <code>String</code>, in your class.</p> <hr /> <p><strong>Reference:</strong></p> <ul> <li><a href="http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html" rel="nofollow">Angelika Langer - Java Generics FAQ</a> <ul> <li><a href="http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html#FAQ002" rel="nofollow">How to define Generic Type</a></li> </ul></li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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