kid
kid

Reputation: 11

Is it possible to overload a method that takes the same data structure but different data types?

Is it possible to overload a method that takes a particular data structure with different types? For example first a string array, then an int array?

I have two hashmaps in my code and I am trying to print out their key, value pairs. The first hashmap takes string arraylists as both its key and value. The second one takes strings as keys and string arraylists as values:

public static void printMap(HashMap<ArrayList<String>, ArrayList<String>> thisMap){
    int i = 0;
    for(ArrayList<String> key : thisMap.keySet()){
        System.out.println(i + " " + key + " >> " + thisMap.get(key).toString());
        System.out.println(" ");
        i++;
    }
}

public static void printMap(HashMap<String, ArrayList<String>> thisMap){
    int i = 0;
    for(String key : thisMap.keySet()){
        System.out.println(i + " " + key + " >> " + thisMap.get(key));
        System.out.println(" ");
        i++;
    }
}

I tried to overload a single method to print both maps but keep getting this error:

java: name clash: printMap(java.util.HashMap<java.util.ArrayList<java.lang.String>,java.util.ArrayList<java.lang.String>>) 
and printMap(java.util.HashMap<java.lang.String,java.util.ArrayList<java.lang.String>>) 
have the same erasure.

what am I doing wrong?

Upvotes: 1

Views: 64

Answers (1)

Oskar Grosser
Oskar Grosser

Reputation: 3434

At compilation, Java performs Type Erasure. During that process, your parameters become plain ArrayList types. As such, their erasure is the same, hence your error.

In my limited experience, solutions to avoid clashes could be to:

  1. Use different (e.g. custom) classes, or
  2. Change the method names.

1. Use different classes

You can define custom classes that extend HashMap:

public class ArrayKeyHashMap<K, V> extends HashMap<ArrayList<K>, V> {
  // Constructors ...
}
public class StringKeyHashMap<V> extends HashMap<String, V> {
  // Constructors ...
}

public class Example {
  public static void printMap(ArrayKeyHashMap<String, ArrayList<String>> thisMap) {
    // ...
  }
  public static void printMap(StringKeyHashMap<ArrayList<String>> thisMap) {
    // ...
  }
}

This way, your method signatures will differ even after type erasure, since literally different classes are used.

2. Change method names

By changing the method names you unfortunately do not overload the methods anymore, but you avoid the issue of having clashes after type erasure:

public class Example {
  public static void printArrayArrayMap(HashMap<ArrayList<String>, ArrayList<String>> thisMap) {
    // ...
  }
  public static void printStringArrayMap(HashMap<String, ArrayList<String>> thisMap) {
    // ...
  }
}

Upvotes: 1

Related Questions