fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. class Ideone
  6. {
  7. // These 3 choices are the only type-safe things we can do
  8. private static <T> Map<T, List<T>> getStuff() {
  9. // return new HashMap<>();
  10.  
  11. // return null;
  12.  
  13. Map<T, List<T>> map = new HashMap<>();
  14. map.put(null, null);
  15. return map;
  16. }
  17.  
  18. // If we want a non-empty map, we have to cast it. But then we can't guarantee it matches
  19. // the type that was inferred
  20. private static <T> Map<T, List<T>> getStuffBad() {
  21. Map map = new HashMap();
  22. map.put("a", Collections.emptyList());
  23. return (Map<T, List<T>>) map;
  24. }
  25.  
  26. public static void main (String[] args) throws java.lang.Exception {
  27. // The same getStuff() call works regardless of whether we want strings or integers
  28. // The only way this is provable type safe is an empty map or null.
  29. Map<String, List<String>> strMap = getStuff();
  30. Map<Integer, List<Integer>> intMap = getStuff();
  31.  
  32. strMap.put("a", Collections.emptyList());
  33. System.out.println(strMap);
  34. intMap.put(1, Collections.emptyList());
  35. System.out.println(intMap);
  36.  
  37. // We ask for an int map, which is allowed
  38. Map<Integer, List<Integer>> badIntMap = getStuffBad();
  39. try {
  40. for (Integer i : badIntMap.keySet()) {
  41. // But it has a string in it, which throws when we access a non-string method
  42. i.intValue();
  43. }
  44. }
  45. catch (Exception e) {
  46. System.out.println(e.getMessage());
  47. }
  48. }
  49. }
Success #stdin #stdout 0.12s 50876KB
stdin
Standard input is empty
stdout
{null=null, a=[]}
{null=null, 1=[]}
class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')