FacelessTiger FacelessTiger - 27 days ago 7
Java Question

java take different list types with same method name

Is it possible to have multiple methods with the same name but takes in different List types. This of course works through overriding regularly but java is unable to tell the difference between two different List types. Is there a way around this other than having different names? For example:

/**
* Prints a given in list, only works on numerical types
*/
public static void printList(List list) {
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i));
if (i != list.size() - 1) System.out.print(", ");
}
System.out.println();
}


would not work if we have

/**
* Prints a given in list of Vector3i
*/
public static void printList(List<Vector3i> list) {
for (int i = 0; i < list.size(); i++) {
System.out.print("(");
System.out.print(list.get(i).x);
System.out.print(", ");
System.out.print(list.get(i).y);
System.out.print(", ");
System.out.print(list.get(i).z);
System.out.print(")");
if (i != list.size() - 1) System.out.print(", ");
}
System.out.println();
}


in the same class.

Answer

You cannot overload methods where you have a generic type like List<T>, because of Java type erasure. Both methods would have the same signature at runtime, namely void printList(List list), which is impossible.

However, you can always override toString or implement a custom print function in your classes and have a single printList method instead of two, which is the way to go here.

Here is an example:

public class Vector3i {

    // Do stuff...

    @Override
    public String toString() { 
        return "(" + x + ", " + y + ", " + z +")";
    }
}

And your print function:

public static <T> void printList(List<T> list) {
    for (int i = 0; i < list.size(); i++) {
        System.out.print(list.get(i).toString());
        if (i != list.size() - 1)
            System.out.print(", ");
    }
    System.out.println();
}