2012-08-10 86 views
1

我有这个getResult(),输入参数略有变化。一个Mapvalue作为一个字符串数组,一个字符串作为anor。Java方法重载错误

但是我看到一个错误: 不会重载支持泛型?

public class App 
{ 

public void getResult(Map<String, String[]> map) { 

} 
public void getResult(Map<String, String> map) { 

} 

}

我看到这个错误:方法的getResult(地图)具有相同的擦除的getResult(图) - 2型应用 另一种方法我想Java是标本兼治刚刚地图等是这个错误。

模仿此行为的最佳方法是什么?

感谢

+4

我认为你需要重新格式化。 – 2012-08-10 20:25:34

+2

这不是有效的Java! – jn1kk 2012-08-10 20:25:35

+0

yaa ...一些零件如何消失。我重新格式 – javaMan 2012-08-10 20:28:06

回答

4

一个重载的规则是与类型参数的方法不能有相同的签名擦除后。见the Java Language Specification, §8.4.8.3。规范中的相关文本是:

It is a compile-time error if a type declaration T has a member method m1 and there exists a method m2 declared in T or a supertype of T such that: . . . The signature of m1 or some method m1 overrides (directly or indirectly) has the same erasure as the signature of m2 or some method m2 overrides (directly or indirectly).

+0

那么,有没有关于方法来做到这一点。一半的时间,我不需要字符串数组和一半的时间我需要它。因此,现在所有使用此代码的应用程序都必须编写代码以将单个字符串转换为字符串数组。有没有解决方案 – javaMan 2012-08-10 20:30:00

+1

@ravi - 你可以给方法不同的名字。我认为唯一的另一种方法是改变参数的数量和/或类型(擦除后)。例如(我不推荐这样做,但是我已经看到它完成了,即使在Java API中),也可以为其中一个方法添加一个伪参数。 – 2012-08-10 20:32:26

2

方法参数只尊重对象的类型,而不是其中的任何泛型。因此,带有Map参数的两个方法将被视为相同,无论它们的通用类型如何。