Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot overload method?

Tags:

java

I have two methods that do a very similar thing: receives a map and then print it to an output file, except that they receives different data type of the map and Java (IntelliJ, in fact) is not allowing me to overload it and says 'parse(Map<String, Long>)' clashes with 'parse(Map<Set<String>, Integer>)'; both methods have same erasure.

Method 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();
    }

Method 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();
    }

I could always make them two different methods with different names but that would make my code looks unnecessary long and wonky, so I am trying to avoid it.

What am I doing wrong here? Please enlighten me.

like image 558
Mint Avatar asked Dec 08 '22 09:12

Mint


1 Answers

that is because of type erasure thingy in java. basically, after compilation, your code will look like this

private static void parse(Map map) {
}

private static void parse(Map map) {
}

looking at the code. why not just make the method signature like this ?

private static void parse(Map<?, ?> map, String fileName) {
}

that way, you would also avoid unnecessary overload.

like image 129
kucing_terbang Avatar answered Dec 26 '22 04:12

kucing_terbang