Skip to content

Instantly share code, notes, and snippets.

@oehme
Created July 12, 2016 16:28
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 oehme/bd548e122c2d47144328cbfb714c2142 to your computer and use it in GitHub Desktop.
Save oehme/bd548e122c2d47144328cbfb714c2142 to your computer and use it in GitHub Desktop.
Why ignoring type safety warnings is bad
List<Foo> specialThings = Lists.newArrayList(); //Foo extends Base
Bean bean = new Bean();
// normally you would correctly get a compile error here,
//but the setter in your example does an unsafe cast that makes this line compile
bean.setStuff(specialThings);
List<Base> things = bean.getStuff();
things.add(new Bar()); // Bar extends Base
//compiles fine, but explodes at runtime as the first element in the list is a Bar, not a Foo
Foo boom = specialThings.get(0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment