fork download
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. import java.util.concurrent.CopyOnWriteArrayList;
  7.  
  8. class Scratch {
  9.  
  10. private static final Map<Class<? extends Entity>, List<Entity>> entities
  11. = new HashMap<>();
  12.  
  13. public static void main(String[] args) {
  14. SomeEnemy firstSomeEnemy = new SomeEnemy();
  15. add(firstSomeEnemy);
  16.  
  17. SomeEnemy secondSomeEnemy = new SomeEnemy();
  18. add(secondSomeEnemy);
  19.  
  20. AnotherEnemy firstAnotherEnemy = new AnotherEnemy();
  21. add(firstAnotherEnemy);
  22.  
  23. AnotherEnemy secondAnotherEnemy = new AnotherEnemy();
  24. add(secondAnotherEnemy);
  25.  
  26. List<SomeEnemy> fetchOne = getAll(SomeEnemy.class);
  27. SomeEnemy firstFetched = fetchOne.get(0);
  28. fetchOne.add(new SomeEnemy());
  29. System.out.println(firstFetched == firstSomeEnemy);
  30.  
  31. remove(firstFetched);
  32. List<SomeEnemy> fetchTwo = getAll(SomeEnemy.class);
  33. SomeEnemy secondFetched = fetchTwo.get(0);
  34. System.out.println(secondFetched == secondSomeEnemy);
  35.  
  36. remove(secondSomeEnemy);
  37. List<SomeEnemy> fetchThree = getAll(SomeEnemy.class);
  38. System.out.println(fetchThree.isEmpty());
  39.  
  40. List<AnotherEnemy> fetchFour = getAll(AnotherEnemy.class);
  41. AnotherEnemy fourthFetched = fetchFour.get(0);
  42. System.out.println(fourthFetched == firstAnotherEnemy);
  43.  
  44. remove(firstAnotherEnemy);
  45. List<AnotherEnemy> fetchFive = getAll(AnotherEnemy.class);
  46. AnotherEnemy fifthFetched = fetchFive.get(0);
  47. System.out.println(fifthFetched == secondAnotherEnemy);
  48.  
  49. remove(secondAnotherEnemy);
  50. List<AnotherEnemy> fetchSix = getAll(AnotherEnemy.class);
  51. System.out.println(fetchSix.isEmpty());
  52.  
  53. }
  54.  
  55. static void add(Entity entity) {
  56. Class<? extends Entity> type = entity.getClass();
  57.  
  58. if (!entities.containsKey(type)) {
  59. entities.put(type, new CopyOnWriteArrayList<>());
  60. }
  61.  
  62. entities.get(type).add(entity);
  63. }
  64.  
  65. private static <T extends Entity> List<T> getAll(Class<? extends T> type) {
  66. return new ArrayList<>(getListCasted(type));
  67. }
  68.  
  69. @SuppressWarnings("unchecked")
  70. private static <T extends Entity> List<T> getListCasted(Class<? extends T> type) {
  71. return (List<T>) entities.getOrDefault(type, Collections.emptyList());
  72. }
  73.  
  74. public static void remove(Entity entity) {
  75. getListCasted(entity.getClass()).remove(entity);
  76. }
  77. }
  78.  
  79. interface Entity {}
  80. interface Enemy extends Entity {}
  81.  
  82. class SomeEnemy implements Enemy {}
  83. class AnotherEnemy implements Enemy {}
Success #stdin #stdout 0.06s 32400KB
stdin
Standard input is empty
stdout
true
true
true
true
true
true