Skip to content

Instantly share code, notes, and snippets.

@nurkiewicz
Last active August 29, 2015 14:03
Show Gist options
  • Save nurkiewicz/7aa630ac3742da666ae4 to your computer and use it in GitHub Desktop.
Save nurkiewicz/7aa630ac3742da666ae4 to your computer and use it in GitHub Desktop.
What will be printed?
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Solution: https://ideone.com/qcHw1f
*/
class Main {
public static void main(String[] args) {
Path path = Paths.get("/");
foo(path);
}
private static void foo(Path... path) {
System.out.println("Vararg");
}
private static void foo(Iterable<Path> path) {
System.out.println("Iterable");
}
}
@pjulien
Copy link

pjulien commented Jun 28, 2014

It will print "Iterable" because Path implements Iterable on path

@rinoto
Copy link

rinoto commented Jun 29, 2014

It will print "Iterable", but the reason is not because Path implements Iterable. See what happens with:

foo(Arrays. <Path>asList(path));
foo(new Path[] {path});

or, if we change the signature of foo(Path... path) to foo(Path path).

So, must have something to do with the varargs, but I don't know why...

@rinoto
Copy link

rinoto commented Jun 29, 2014

Well, Java probably first tries to find a method suitable for the args, and finds foo(Iterable path), because Path implements Iterable.
The lookup for the method with the varargs is just left as a second option, if no method had been found in the first lookup.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment