Skip to content

Instantly share code, notes, and snippets.

@fsarradin
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fsarradin/0f8ca38411b228cf1ea8 to your computer and use it in GitHub Desktop.
Save fsarradin/0f8ca38411b228cf1ea8 to your computer and use it in GitHub Desktop.
Java generics confusion
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;
}
}
@massyl
Copy link

massyl commented May 18, 2015

The problem is when you use raw type

convert(List l);

from this point on, you're confusing the compiler :-) if you take a look to the convert() implementation
the compiler will issue a warning for you( type unsafe conversion)

Never and Ever use raw types : use

List <T> or List<?>

@massyl
Copy link

massyl commented May 18, 2015

in the inner loop if you use String instead of Object and then remove the cast to Double,
you'll get a ClassCastException

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