Last active
August 29, 2015 14:03
-
-
Save nurkiewicz/7aa630ac3742da666ae4 to your computer and use it in GitHub Desktop.
What will be printed?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} | |
} |
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...
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
It will print "Iterable" because Path implements Iterable on path