0

Consider the following code:

public class SimpleTest {
    public static void print(Collection<Object> strings) {
        System.out.println("Collection overload: " + strings);
    }

    public static void print(Object... strings) {
        System.out.println("Vararg overload: " + Arrays.asList(strings));
    }

    @Test
    public void test() {
        List<String> strings = Arrays.asList("hello", "world");
        print(strings);
    }
}

What's your prediction of the output?

It turns out, the correct answer is this!

Vararg overload: [[hello, world]]

If you guessed right, could you please explain why it's not the collection overload?

Update

If I change the collection overload to

   public static void print(Collection<String> strings) {
      System.out.println("Collection overload: " + strings);
   }

or

   public static void print(Collection strings) {
      System.out.println("Collection overload: " + strings);
   }

Then it outputs

Collection overload: [hello, world]
stackoverflower
  • 3,885
  • 10
  • 47
  • 71
  • See also [What is a raw type and why shouldn't we use it?](http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) for the last snippet in your update. – Sotirios Delimanolis Jul 14 '16 at 14:47
  • Not an answer, but for your entertainment, [the documentation says](http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html) "Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called." – jdigital Jul 14 '16 at 14:52

0 Answers0