Method has the same erasure as another method in type

前端 未结 7 776
时光取名叫无心
时光取名叫无心 2020-11-22 05:50

Why is it not legal to have the following two methods in the same class?

class Test{
   void add(Set ii){}
   void add(Set ss){}         


        
7条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 06:42

    I bumped into this when tried to write something like: Continuable callAsync(Callable code) {....} and Continuable> callAsync(Callable> veryAsyncCode) {...} They become for compiler the 2 definitions of Continuable<> callAsync(Callable<> veryAsyncCode) {...}

    The type erasure literally means erasing of type arguments information from generics. This is VERY annoying, but this is a limitation that will be with Java for while. For constructors case not much can be done, 2 new subclasses specialized with different parameters in constructor for example. Or use initialization methods instead... (virtual constructors?) with different names...

    for similar operation methods renaming would help, like

    class Test{
       void addIntegers(Set ii){}
       void addStrings(Set ss){}
    }
    

    Or with some more descriptive names, self-documenting for oyu cases, like addNames and addIndexes or such.

提交回复
热议问题