Last active
August 29, 2015 14:21
-
-
Save fsarradin/0f8ca38411b228cf1ea8 to your computer and use it in GitHub Desktop.
Java generics confusion
This file contains hidden or 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 org.junit.Test; | |
import java.util.Arrays; | |
import java.util.List; | |
public class GenericsTest { | |
@Test | |
public void should_convert___well_huh() throws Exception { | |
List<Double> list = Arrays.asList(12.0, 3.0); | |
List<String> result = convert(list); | |
for (Object s : result) { | |
final Double value = (Double) s; | |
System.out.println(value); | |
// no compilation error, print 12.0 3.0 | |
} | |
} | |
<T> List<T> convert(List l) { | |
return l; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
in the inner loop if you use String instead of Object and then remove the cast to Double,
you'll get a ClassCastException