java - Generics compile issue: incompatible types -


this question has answer here:

given simple class:

    import java.util.collection;      public class generictest<t> {       public collection<string> getkeys() {         return null;       }       public void copy(generictest a_from) {         (string x : a_from.getkeys()) {          }       }     } 

i getting following compile error, don't understand why.

    error: incompatible types     (string x : a_from.getkeys()) {       required: string       found:    object 

the error goes away if change parameter copy() method generictest<t>, not want. copy() method valid on type of generictest, not generictest<t>.

this not how create generic class. if use raw type of generic class, parameterized type used inside class, loose type information. so, generictest raw type, getkeys() method signature changes to:

public collection getkeys() {     return null; } 

so, if iterate on getkeys() method of generictest raw type, object, , not string, don't see why expect.

from jls section 4.8 - raw types:

the type of constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) m of raw type c not inherited superclasses or superinterfaces raw type corresponds erasure of type in generic declaration corresponding c.


you should use generictest<t> parameter type in method, instead of raw type. , change return type of getkeys collection<t>.

change class to:

public class generictest<t> {     public collection<t> getkeys() {       return null;     }     public void copy(generictest<t> a_from) {       (t x : a_from.getkeys()) {        }    } } 

the type t infered parameterized type create generic class. generictest<string>, t infered string, in class.


reference:


Comments

Popular posts from this blog

assembly - 8086 TASM: Illegal Indexing Mode -

Java, LWJGL, OpenGL 1.1, decoding BufferedImage to Bytebuffer and binding to OpenGL across classes -

javascript - addthis share facebook and google+ url -