fork download
  1. import java.util.*;
  2.  
  3. class Builder<T extends Builder> {
  4. private String name;
  5. private List<String> friends;
  6.  
  7. T setName(String name) {
  8. this.name = name;
  9. return (T) this;
  10. }
  11.  
  12. T setFriends(List<String> friends) {
  13. this.friends = friends;
  14. return (T) this;
  15. }
  16.  
  17. T uncheckedOops() {
  18. // setName returns a raw type Builder
  19. setName("Foobar")
  20. // oops, passing List<Integer> to List<String> compiles,
  21. // because the parameter type of T.setFriends is erased to just List
  22. .setFriends(Arrays.asList(1, 2, 3));
  23. return (T) this;
  24. }
  25.  
  26. public static void main(String[] args) {
  27. Builder<?> b = new Builder<>().uncheckedOops();
  28.  
  29. try {
  30. for (String friend : b.friends)
  31. System.out.println(friend);
  32. } catch (Exception x) {
  33. x.printStackTrace(System.out);
  34. }
  35. }
  36. }
Success #stdin #stdout 0.07s 27704KB
stdin
Standard input is empty
stdout
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
	at Builder.main(Main.java:30)