我有两个方法可以做非常相似的事情:接收地图,然后将其打印到输出文件,只是它们接收的地图的数据类型不同,并且Java (实际上是IntelliJ)不允许我重载它并指定'parse(Map<String, Long>)' clashes with 'parse(Map<Set<String>, Integer>)'; both methods have same erasure。
方法A:
private static void parse(Map<String, Long> map) {
PrintWriter output = null;
try {
output = new PrintWriter("output1.csv");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
assert output != null;
map.entrySet().forEach(output::println);
output.close();
}方法B:
private static void parse(Map<Set<String>, Integer> map) {
PrintWriter output = null;
try {
output = new PrintWriter("output2.csv");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
assert output != null;
map.entrySet().forEach(output::println);
output.close();
}我总是可以用不同的名字把它们变成两个不同的方法,但这会使我的代码看起来不必要的冗长和不可靠,所以我尽量避免这样做。
我到底做错了什么?请开导我。
发布于 2020-11-17 11:17:39
这是因为java中的类型擦除。基本上,在编译之后,您的代码将如下所示
private static void parse(Map map) {
}
private static void parse(Map map) {
}看代码。为什么不这样做方法签名呢?
private static void parse(Map<?, ?> map, String fileName) {
}这样,您还可以避免不必要的过载。
发布于 2020-11-17 11:10:54
你可以用不同的参数,不同数量的参数和不同类型的参数来重载一个方法。在您的示例代码中,Java将这两个方法视为相同的,因为它们具有相同的输入参数,即Map,您可以在其中一个方法中添加另一个参数以使它们工作。
发布于 2020-11-17 11:17:52
不,你可以。它们都是一样的,而且,使用参数的单个语句是map.entrySet(),它是https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#entrySet--
因此,您只需使用接口Map,以下是如何在地图Generic Map Parameter java上实现generis的示例
https://stackoverflow.com/questions/64868727
复制相似问题