1

I try to write a generic method to print:

  1. A list of element such as list of Integer, String, etc.
  2. A list of T[] such as List<String[]>, List<Integer[]> etc.

I have following two methods:

public static <T> void printList(List<T> list){
    for(T n : list) {
        System.out.print("[" + n + "]");
    }
}
public static <T> void printList(List<T[]> list){
    for(T[] arr: list) {
        for(T n : arr){
            System.out.print("[" + n + "]");
        }
    }
}

I got compile error:

public static <T> void printList(List<T[]> list){
 where T#1,T#2 are type-variables:
 T#1 extends Object declared in method <T#1>printList(List<T#1[]>)
 T#2 extends Object declared in method <T#2>printList(List<T#2>)

Is there any way I can have a method printList for List<T> and List<T[]>?

Ruslan
  • 6,090
  • 1
  • 21
  • 36
1234
  • 539
  • 3
  • 12
  • 1
    You can't have multiple methods with the same signature. You'll need to change the name or parameters of one of them. – azurefrog Mar 05 '19 at 17:48
  • [This question](https://softwareengineering.stackexchange.com/questions/130088/how-to-resolve-methods-with-the-same-name-and-parameter-types) over on the software engineering stack might be helpful to you in a more general design sense. – azurefrog Mar 05 '19 at 17:51
  • 1
    As a rule of thumb, don't mix generics and arrays. – Lew Bloch Mar 05 '19 at 18:13

1 Answers1

2

At the runtime, your List<T> and a List<T[]> are exactly the same since the generic type has been erased by the compiler. Therefore both of methods has the same signature, and you the compile error. To fix that just give a different name to one of methods.

See more about erasure concept What is the concept of erasure in generics in Java?, Java spec

Ruslan
  • 6,090
  • 1
  • 21
  • 36