java - Method has the same erasure as another method in type -


why not legal have 2 methods in same class?

class test{    void add(set<integer> ii){}    void add(set<string> ss){} } 

i compilation error

method add(set) has same erasure add(set) method in type test.

while can work around it, wondering why javac doesn't this.

i can see in many cases, logic of 2 methods similar , replaced single

public void add(set<?> set){} 

method, not case.

this annoying if want have 2 constructors takes arguments because can't change name of 1 of constructors.

this limitation part of language syntax, not java runtime itself. essentially, rule intended avoid conflicts in legacy code still uses raw types.

a compiler javac reject type of overloading, if create class through other means (writing own compiler, or using byte-code engineering library asm) signatures differ type parameters, javac compiler resolve calls correct method in class.

here's illustration of why not allowed, drawn jls. suppose, before generics introduced java, wrote code this:

class collectionconverter {   list tolist(collection c) {...} } 

you extend class, this:

class overrider extends collectionconverter{   list tolist(collection c) {...} } 

after introduction of generics, decided update library.

class collectionconverter {   <t> list<t> tolist(collection<t> c) {...} } 

you aren't ready make updates, leave overrider class alone. in order correctly override tolist() method, language designers decided raw type "override-equivalent" generified type. means although method signature no longer formally equal superclass' signature, method still overrides.

now, time passes , decide ready update class. screw little, , instead of editing existing, raw tolist() method, add new method this:

class overrider extends collectionconverter {   @override   list tolist(collection c) {...}   @override   <t> list<t> tolist(collection<t> c) {...} } 

because of override equivalence of raw types, both methods in valid form override tolist(collection<t>) method. of course, compiler needs resolve single method. eliminate ambiguity, classes not allowed have multiple methods override-equivalent—that is, multiple methods same parameter types after erasure.

the key language rule designed permit continued use of raw types, not limitation arising erasure of type parameters.

if eliminate legacy code (for example, using own, not-strictly-java language), type of overload functions perfectly. because method resolution occurs @ compile-time, before erasure, type reification not required make work.


Comments

Popular posts from this blog

IF statement in MySQL trigger -

c++ - What does MSC in "// appease MSC" comments mean? -

javascript - Blogger related post gadget image Resize s72-c [ Need Expert Help ] -