Commits

Shuji Watanabe committed 476510f

registerでa_3000を与えるとmapの1000から削除されている

Comments (0)

Files changed (2)

src/main/java/tddbc/lrucache/WeightContainer.java

 public class WeightContainer {
     private final List<String> list = new ArrayList<String>();
     private final Map<String, Long> weights = new TreeMap<String, Long>();
-    private final SortedMap<Long, Set<String>> map = new TreeMap<Long, Set<String>>();
+    final SortedMap<Long, Set<String>> map = new TreeMap<Long, Set<String>>();
 
     public int size() {
         return list.size();
     public void register(String element, long weight) {
         if (list.contains(element)) {
             list.remove(element);
+            Long oldWeight = getWeight(element);
+            Set<String> set = map.get(oldWeight);
+            if (set != null) {
+                set.remove(element);
+                if (set.isEmpty()) map.remove(oldWeight);
+            }
         }
         list.add(element);
         Set<String> set = map.get(weight);
         Long weight = weights.remove(element);
         Set<String> set = map.get(weight);
         set.remove(element);
-        if (set.isEmpty()){
-            map.remove(weight);        
+        if (set.isEmpty()) {
+            map.remove(weight);
         }
     }
 

src/test/java/tddbc/lrucache/WeightContainerTest.java

             assertThat(sut.get(0), is("b"));
             assertThat(sut.get(1), is("a"));
         }
+        
+        @Test
+        public void registerでa_3000を与えるとgetWeigtで3000が取得できる() throws Exception {
+            // Exercise
+            sut.register("a", 3000);
+            // Verify
+            assertThat(sut.getWeight("a"), is(3000L));
+        }
+        
+        @Test
+        public void registerでa_3000を与えるとmapの1000から削除されている() throws Exception {
+            // Exercise
+            sut.register("a", 3000);
+            // Verify
+            assertThat(sut.map.get(1000L), is(nullValue()));
+            assertThat(sut.map.get(3000L), is(notNullValue()));
+            assertThat(sut.map.get(3000L).contains("a"), is(true));
+        }
+
+        
     }
 
     public static class abcが追加された場合 {