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 rule intended avoid conflicts in legacy code still uses raw types.

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 maintain compatibility old code using raw types. not limitation required erasure of type parameters; because method resolution occurs @ compile-time, adding generic types method identifier have been sufficient.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

order - Notification for user in user account opencart -