Skip to content

Commit c0a2f6d

Browse files
yantzuchingor13
authored andcommitted
fix arraymap iterator remove issue (#371)
* fix arraymap iterator remove issue * fix code style
1 parent 13e528d commit c0a2f6d

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

google-http-client/src/main/java/com/google/api/client/util/ArrayMap.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,7 @@ public Map.Entry<K, V> next() {
381381
throw new NoSuchElementException();
382382
}
383383
this.nextIndex++;
384+
this.removed = false;
384385
return new Entry(index);
385386
}
386387

@@ -390,6 +391,7 @@ public void remove() {
390391
throw new IllegalArgumentException();
391392
}
392393
ArrayMap.this.remove(index);
394+
this.nextIndex--;
393395
this.removed = true;
394396
}
395397
}

google-http-client/src/test/java/com/google/api/client/util/ArrayMapTest.java

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@
1616

1717
import junit.framework.TestCase;
1818

19+
import java.util.Iterator;
20+
import java.util.Map;
21+
1922
/**
2023
* Tests {@link ArrayMap}.
2124
*
@@ -109,4 +112,52 @@ public void testHashCode() {
109112

110113
assertTrue(map.hashCode() > 0);
111114
}
115+
116+
public void testIteratorRemove1() {
117+
ArrayMap<String, String> map = new ArrayMap<String, String>();
118+
map.put("a", "a");
119+
map.put("b", "b");
120+
map.put("c", "c");
121+
Iterator<Map.Entry<String, String>> iter = map.entrySet().iterator();
122+
while (iter.hasNext()) {
123+
Map.Entry<String, String> entry = iter.next();
124+
if (!"all".equalsIgnoreCase(entry.getKey())) {
125+
iter.remove();
126+
}
127+
}
128+
assertEquals(0, map.size());
129+
}
130+
131+
public void testIteratorRemove2() {
132+
ArrayMap<String, String> map = new ArrayMap<String, String>();
133+
map.put("a", "a");
134+
map.put("b", "b");
135+
map.put("c", "c");
136+
Iterator<Map.Entry<String, String>> iter = map.entrySet().iterator();
137+
while (iter.hasNext()) {
138+
Map.Entry<String, String> entry = iter.next();
139+
if ("b".equalsIgnoreCase(entry.getKey())) {
140+
iter.remove();
141+
}
142+
}
143+
assertEquals(2, map.size());
144+
assertEquals("a", map.get("a"));
145+
assertEquals("c", map.get("c"));
146+
}
147+
148+
public void testIteratorRemove3() {
149+
ArrayMap<String, String> map = new ArrayMap<String, String>();
150+
map.put("a", "a");
151+
map.put("b", "b");
152+
map.put("c", "c");
153+
Iterator<Map.Entry<String, String>> iter = map.entrySet().iterator();
154+
while (iter.hasNext()) {
155+
Map.Entry<String, String> entry = iter.next();
156+
if (!"b".equalsIgnoreCase(entry.getKey())) {
157+
iter.remove();
158+
}
159+
}
160+
assertEquals(1, map.size());
161+
assertEquals("b", map.get("b"));
162+
}
112163
}

0 commit comments

Comments
 (0)