Created
January 25, 2012 12:58
-
-
Save fcamblor/1676147 to your computer and use it in GitHub Desktop.
Java Puzzler #2
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
What happens when this code is compiled/executed ? | |
public class A<T> { | |
public List<T> listOfTs = new ArrayList<T>(); | |
public List<Long> listOfLongs = Arrays.asList(1l, 2l, 4l); | |
public A(List<T> _t){ this.listOfTs = _t; } | |
public static void main(String[] args){ | |
hello(new A<String>(Arrays.asList("1", "2", "4"))); | |
} | |
public static void hello(A a){ | |
for(Long l : a.listOfLongs){ System.out.println( l ); } /* (1) */ | |
for(String s : a.listOfTs){ System.out.println(s); } /* (2) */ | |
} | |
} | |
1/ Doesn't compile at line (1) | |
2/ Doesn't compile at line (2) | |
3/ Doesn't compile at both lines (1) and (2) | |
4/ Exception at runtime at line (1) | |
5/ Exception at runtime at line (2) | |
6/ It display "1, 2, 4" in the console, two times (but heh, would I be dumb enough to ask you this question if it was this answer ?) | |
The answer is in the JLS : http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#112736 (thanks to @jnegre_org :-)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment