ayman
ayman

Reputation: 49

generic methods is used to eliminate overloaded methods

I read a little about generic methods , and I found that it is used to eliminate overloaded methods.

public static void main(String[] args) {
    Integer arr[] = { 12, 55, 66, 54 };

    printArray(arr);
}

public static <T> void printArray(T arr[]) {
    for (T a : arr) {
        System.out.print(a.toString() + " ");
    }
    System.out.println();
}

before knowing anything about generic methods I used to do something like the following :

public static void main(String[] args) {
    Integer arr[] = { 12, 55, 66, 54 };

    printArray(arr);
}

public static void printArray(Object arr[]) {
    for (Object a : arr) {
        System.out.print(a.toString() + " ");
    }
    System.out.println();
}

what is the differences between the two ways ...?

Upvotes: 0

Views: 86

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198211

For the specific use case you've mentioned, there is no difference, since all objects have a toString() method. If you wanted to return a T or T[], or you needed T to implement some generic interface, or the like, then you would need a generic method. (That said, generics tend to be used more with collections than arrays.)

Upvotes: 6

Related Questions